zip as iterator and bad/good practices
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Sat Jun 13 03:17:23 EDT 2015
On Sat, 13 Jun 2015 13:32:59 +0800, jimages wrote:
> I am a newbie. I also have been confused when I read the tutorial. It
> recommends make a copy before looping. Then I try.
> #--------------------------
> Test = [1, 2]
> For i in Test:
> Test.append(i)
> #--------------------------
You don't make a copy of Test here. You could try this instead:
Test = [1, 2]
copy_test = Test[:] # [:] makes a slice copy of the whole list
for i in copy_test: # iterate over the copy
Test.append(i) # and append to the original
print(Test)
But an easier way is:
Test = [1, 2]
Test.extend(Test)
print(Test)
> But when i execute. The script does not end. I know there must something
> wrong. So I launch debugger and deserve the list after each loop. And I
> see:
> Loop 1: [ 1, 2, 1]
> Loop 2: [ 1, 2, 1, 2]
> Loop 3: [ 1, 2, 1, 2, 1]
> Loop 4: [ 1, 2, 1, 2, 1, 2]
> ......
> So you can see that loop will *never* end. So I think you regard the 'i'
> as a pointer.
i is not a pointer. It is just a variable that gets a value from the
list, the same as:
# first time through the loop
i = Test[0]
# second time through the loop
i = Test[1] # the second item
The for loop statement:
for item in seq: ...
understands sequences, lists, and other iterables, not "item". item is
just an ordinary variable, nothing special about it. The for statement
takes the items in seq, one at a time, and assigns them to the variable
"item". In English:
for each item in seq ...
or to put it another way:
get the first item of seq
assign it to "item"
process the block
get the second item of seq
assign it to "item"
process the block
get the third item of seq
assign it to "item"
process the block
...
and so on, until seq runs out of items. But if you keep appending items
to the end, it will never run out.
> Change code to this
> #--------------------------
> Test = [1, 2]
> For i in Test[:] :
> Test.append(i)
> #--------------------------
Yes, this will work.
--
Steve
More information about the Python-list
mailing list