Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #77716 > unrolled thread
| Started by | Peter Otten <__peter__@web.de> |
|---|---|
| First post | 2014-09-09 09:13 +0200 |
| Last post | 2014-09-09 09:13 +0200 |
| Articles | 1 — 1 participant |
Back to article view | Back to comp.lang.python
This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by
below is the oldest one visible, not the original post.
Re: Passing a list into a list .append() method Peter Otten <__peter__@web.de> - 2014-09-09 09:13 +0200
| From | Peter Otten <__peter__@web.de> |
|---|---|
| Date | 2014-09-09 09:13 +0200 |
| Subject | Re: Passing a list into a list .append() method |
| Message-ID | <mailman.13889.1410246814.18130.python-list@python.org> |
JBB wrote:
> I have a list with a fixed number of elements which I need to grow; ie.
> add rows of a fixed number of elements, some of which will be blank.
>
> e.g. [['a','b','c','d'], ['A','B','C','D'], ['', 'aa', 'inky', ''], ['',
> 'bb', 'binky', ''], ... ]
>
> This is a reduced representation of a larger list-of-lists problem that
> had me running in circles today.
>
> I think I figured out _how_ to get what I want but I am looking to
> understand why one approach works and another doesn't.
The actual problem is that you are appending the same list multiple times.
In nuce:
>>> inner = [1, 2, 3]
>>> outer = [inner, inner, inner]
Remember that outer[0] is inner just like the two other items of the outer
list:
>>> outer[0] is inner
True
>>> outer[1] is inner
True
>>> outer[2] is inner
True
So
>>> outer[0][0] = 42
effectively changes inner
>>> inner
[42, 2, 3]
which is reflected in the following output:
>>> outer
[[42, 2, 3], [42, 2, 3], [42, 2, 3]]
With list(inner) you create a (shallow) copy of inner
>>> inner = [1, 2, 3]
>>> outer = [list(inner), list(inner), list(inner)]
>>> outer[0] is inner
False
and a subsequent assignment changes only that specific copy of inner:
>>> outer[0][0] = 42
>>> outer
[[42, 2, 3], [1, 2, 3], [1, 2, 3]]
So the key to the solution is that you create a new list on every iteration
of the loop. With that in mind I'd write
for a, b, in zip(qq, rr):
proc_file.append(["", a, b, ""])
or alternatively if the actual inner list is more complex
template = ["", "", "", ""]
for p in zip(qq, rr):
inner = list(template)
inner[1:3] = p
proc_file.append(inner)
> 1) What does NOT work as desired:
> proc_file.append((blank_r)) # Add a row of blanks
> proc_file[i+2][1] = j[0]
> proc_file[i+2][2] = j[1]
> 2) What works as desired:
> proc_file.append(list(blank_r)) # Change it to list(blank_r) and it
> works
> proc_file[i+2][1] = j[0]
> proc_file[i+2][2] = j[1]
> print len(proc_file), blank_r, proc_file
Back to top | Article view | comp.lang.python
csiph-web