Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Last Iteration in For Loop

Tags:

python

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.

like image 310
Sivasubramaniam Arunachalam Avatar asked Mar 08 '11 10:03

Sivasubramaniam Arunachalam


4 Answers

To convert a 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 string, you just do ",".join(l).

like image 105
Björn Pollex Avatar answered Sep 27 '22 23:09

Björn Pollex


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]
like image 38
Martin Stone Avatar answered Sep 27 '22 23:09

Martin Stone


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
like image 40
jfs Avatar answered Sep 28 '22 00:09

jfs


actually when a for loop in python ends the name that it bound is still accessible 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 like:

with Timer() as T:
    pass # do something
print T.format() # prints 0.34 seconds
like image 42
Dan D. Avatar answered Sep 28 '22 01:09

Dan D.