Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

understanding for loops with reference to list containers in python

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.

like image 265
Jose Avatar asked May 06 '11 21:05

Jose


People also ask

Can you use for loops with lists in Python?

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.

Can we use for loop for 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.

What is the for loop in Python?

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.


1 Answers

When python executes v = [0, 0, 0], it's

  1. Creating a new list object with three zeroes in it.
  2. Assigning a reference to the new list to a label called 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.

like image 105
recursive Avatar answered Oct 30 '22 06:10

recursive