Is there any simple way to find the Last Iteration of the for Loop in Python? I just want to convert a list to CSV.
-
6No. But maybe if you explain your actual problem, we can suggest an alternative solution?Björn Pollex– Björn Pollex2011-03-08 10:17:03 +00:00Commented Mar 8, 2011 at 10:17
-
2I wonder if the standard csv module might solve your problem another way.Martin Stone– Martin Stone2011-03-08 10:38:27 +00:00Commented Mar 8, 2011 at 10:38
-
1I'm not sure why none of the replies to this question actually answer it...2rs2ts– 2rs2ts2013-05-30 15:45:17 +00:00Commented May 30, 2013 at 15:45
-
Here's an actual answer for the generic situation.. stackoverflow.com/a/1630350/804616trss– trss2014-07-13 09:45:14 +00:00Commented Jul 13, 2014 at 9:45
-
"Is there any simple way to find the Last Iteration of the for Loop in Python? I just want to convert a list to CSV." These are two separate questions, both of which have much better versions, so I closed this as duplicates of both. Aside from that, it is not at all clear *why knowing the "last iteration" would help" in the conversion task.Karl Knechtel– Karl Knechtel2023-03-29 05:47:07 +00:00Commented Mar 29, 2023 at 5:47
Add a comment
|
5 Answers
Your best solution is probably to use the csv module, as suggested elsewhere. However, to answer your question as stated:
Option 1: count your way through using enumerate()
for i, value in enumerate(my_list):
print value,
if i < len(my_list)-1:
print ", followed by"
Option 2: handle the final value (my_list[-1]) outside the loop
for value in my_list[:-1]:
print value, ", followed by"
print my_list[-1]
Comments
To convert a list to csv you could use csv module:
import csv
list_of_lists = ["nf", [1,2]]
with open('file', 'wb') as f:
csv.writer(f).writerows(list_of_lists)
The 'file' file would be:
n,f
1,2
Comments
Not exactly what you want:
>>> for i in range(5):
print(i)
else:
print("Last i is",i)
0
1
2
3
4
Last i is 4
Edited: There is csv module in standard library, or simply ','.join(LIST)