[Tutor] Problem with nested for-in (Alan Gauld)

Kent Johnson kent37 at tds.net
Thu Jan 29 16:26:14 CET 2009

On Thu, Jan 29, 2009 at 8:55 AM, emmanuel.delaborde
<emmanuel.delaborde at cimex.com> wrote:
>> I suspect that you need to reset the reader iterator to the start.
>> I'm sure there will be something in the iterator protocol to do
>> that

No, in general iterators cannot be reset.

>> but failing that you would need to change the inner loop to:
>> for line2 in csv.reader(open("CATEGORYLIST.csv","r"))
>> which will re-read the file and create a new iterator each time...
>> resetting the iterator would be faster I suspect.

Better would be to read the lines into a list before the first loop:
lines2 = list(csv.reader(("CATEGORYLIST.csv","r"))

Then lines2 can be iterated as many times as you like.

What are you trying to do? Generally problems of the form
for item in list1:
  if item in list2:
    # do something with item

have better solutions using sets or dicts in place of list2.


More information about the Tutor mailing list