简体   繁体   中英

For loop changes original list variable

Quick question from someone with limited Python experience. So I have some lists inside a list. I want to iterate through it, append something to each iteration, and then store that in a different list.

For example:

var=[[1],[2],[3]]
var2 = []

for item in var:
    var2.append(item.append("x"))

However, rather than the expected output for var2 of [[1, 'x'], [2, 'x'], [3, 'x']] I get [None, None, None]

I was planning to reuse my original variable, var , for a different purpose. However, var is now equal to [[1, 'x'], [2, 'x'], [3, 'x']]

What is going on here?

The append function modifies its input. So when you call item.append(...) , you are modifying item , which is a reference to one of the elements in var .

You can minimally reproduce this via

var=[[1],[2],[3]]

for item in var:
    item.append("x")

In addition, the return value of append is None , so you're effectively calling var2.append(None) for each item, explaining your var2 result.

To avoid this, use a non-destructive method that returns the value you want, such as

var=[[1],[2],[3]]
var2 = []

for item in var:
    var2.append(item + ["x"])

Or, better still,

var=[[1],[2],[3]]
var2 = [item + ["x"] for item in var]

If you refer to the docs list.append as well as others return None and that's what you're appending. Therefore you need to concatenate or extend the list while returning the value. I suggest using item + ['x'] so your loop would look as follows:

for item in var:
    var2.append(item + ['x'])

Although why not just use a list comprehension for this?

var=[[1],[2],[3]]
var2 = [item + ['x'] for item in var]

Results:

[[1, 'x'], [2, 'x'], [3, 'x']]

Your for loop is the culprit. This is not that hard but we have to make sure what is going on in the nested list appends.

My solution to this would be:

var=[[1],[2],[3]]
var2 = []

for i in range(len(var)):
  list = []
  list.append(var[i][0])
  list.append('x')
  var2.append(list)

print(var)
print(var2)
>>> [[1], [2], [3]]
>>> [[1, 'x'], [2, 'x'], [3, 'x']]

Even though it may be intuitive to write:

for list in var:
  list.append('x')
  var2.append(newList)

This will change the values in the lists in the original var list as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM