Last Python iteration for loop

Is there an easy way to find the last iteration of a for loop in Python? I just want to convert the list to CSV.

+8
python
source share
5 answers

To convert the list to CSV, use the join function:

 >>> lst = [1,2,3,4] >>> ",".join(str(item) for item in lst) "1,2,3,4" 

If the list already contains only a string, you simply do ",".join(l) .

+12
source share

To convert a list to csv, you can use the csv module:

 import csv list_of_lists = ["nf", [1,2]] with open('file', 'wb') as f: csv.writer(f).writerows(list_of_lists) 

File 'file' :

 n,f 1,2 
+12
source share

The best solution is probably to use the csv module, as suggested elsewhere. However, to answer your question as indicated:

Option 1: count your way with enumerate ()

 for i, value in enumerate(my_list): print value, if i < len(my_list)-1: print ", followed by" 

Option 2: process the final value ( my_list[-1] ) outside the loop

 for value in my_list[:-1]: print value, ", followed by" print my_list[-1] 
+10
source share

in fact, when the for loop in python ends, the name that it is bound to is still available and bound to its last value:

 for i in range(10): if i == 3: break print i # prints 3 

I use this trick with with as follows:

 with Timer() as T: pass # do something print T.format() # prints 0.34 seconds 
+9
source share

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 a csv module in the standard library or just ','.join(LIST)

+4
source share

All Articles