0

For loops printing lists

So if I make a list of people say.. greatppl = ['name1', 'name2', 'name3'] then I append to it and insert by doing greatppl.insert (0, 'name0') greatppl.append ('name4') when i print greatppl it shows the list but when i create a for loop for greatppl like so: for greatppl in greatppl: print (greatppl) it just prints all the names then when i print greatppl again it outputs the last character in the last name print (greatppl) so in this case 4 would be the output why is that?

11th Dec 2016, 8:32 AM
Eric Reed
Eric Reed - avatar
2 odpowiedzi
+ 1
in loops like "for a in b", avoid to give the same names to iterator and iterable object. i suppose there might be a collapse happened, your list was passed to a generator, and then, using the same name, your list was overwritten by each it's element, so after a loop the name 'greatppl' stores only the last of items. use different name, like: for greathuman in greatppl: print greathuman
11th Dec 2016, 8:40 AM
Demeth
Demeth - avatar
0
ahhh now i understand thanks so much! @Demeth
11th Dec 2016, 5:06 PM
Eric Reed
Eric Reed - avatar