简体   繁体   中英

Iteratively add elements to a list

I am trying to add elements of a list in Python and thereby generate a list of lists. Suppose I have two lists a = [1,2] and b = [3,4,5] . How can I construct the following list:

c = [[1,2,3],[1,2,4],[1,2,5]] ?

In my futile attempts to generate c , I stumbled on an erroneous preconception of Python which I would like to describe in the following. I would be grateful for someone elaborating a bit on the conceptual question posed at the end of the paragraph. I tried (among other things) to generate c as follows:

c = []
for i in b:
   temp = a
   temp.extend([i])
   c += [temp]

What puzzled me was that a seems to be overwritten by temp. Why does this happen? It seems that the = operator is used in the mathematical sense by Python but not as an assignment (in the sense of := in mathematics).

You are not creating a copy; temp = a merely makes temp reference the same list object. As a result, temp.extend([i]) extends the same list object a references :

>>> a = []
>>> temp = a
>>> temp.extend(['foo', 'bar'])
>>> a
['foo', 'bar']
>>> temp is a
True

You can build c with a list comprehension:

c = [a + [i] for i in b]

By concatenating instead of extending, you create a new list object each iteration.

You could instead also have made an actual copy of a with:

temp = a[:]

where the identity slice (slicing from beginning to end) creates a new list containing a shallow copy.

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