My question is regarding the following for loop:
x=[[1,2,3],[4,5,6]]
for v in x:
v=[0,0,0]
here if you print x you get [[1,2,3],[4,5,6]].. so the v changed is not really a reference to the list in x. But when you do something like the following:
x=[[1,2,3],[4,5,6]]
for v in x:
v[0]=0; v[1]=0; v[2] =0
then you get x as [[0,0,0],[0,0,0]]. This kinda gets difficult if the list inside x is quite long, and even doing something like this:
x=[[1,2,3],[4,5,6]]
for v in x:
for i in v:
i = 0
will give me x as [[1,2,3],[4,5,6]]. My best bet is to use for i in xrange(0,3): v[i]=0 .. Though I'd still like to know what's going on here and what the other alternatives are when I have list of lists or more nested lists.
You can use a for loop to create a list of elements in three steps: Instantiate an empty list. Loop over an iterable or range of elements. Append each element to the end of the list.
Using Python for loop to iterate over a list. In this syntax, the for loop statement assigns an individual element of the list to the item variable in each iteration. Inside the body of the loop, you can manipulate each list element individually.
A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string). This is less like the for keyword in other programming languages, and works more like an iterator method as found in other object-orientated programming languages.
When python executes v = [0, 0, 0]
, it's
v
It doesn't matter if v
was a reference to something else before.
If you want to change the contents of the list currently referenced by v
, then you can't use the v =
syntax. You must assign elements to it, like you mentioned, or use slice notation v[:] =
as noted by Sven.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With