for loop without variable

Mike Meyer mwm-keyword-python.b4bdba at mired.org
Fri Jan 11 23:37:30 CET 2008


On Fri, 11 Jan 2008 22:18:22 GMT Neil Hodgson <nyamatongwe+thunder at gmail.com> wrote:

> Marty:
> > I recently faced a similar issue doing something like this:
> >     data_out = []
> >     for i in range(len(data_in)):
> >         data_out.append([])
> 
>     Another way to write this is
> data_out = [[]] * len(data_in)

Not quite. All the other variants give you 23 empty lists. That one
gives you 23 references to one list:

>>> x = [[] for _ in range(23)]
>>> x[1].append(23)
>>> x
[[], [23], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], []]
>>> x = [[]] * 23
>>> x[1].append(23)
>>> x
[[23], [23], [23], [23], [23], [23], [23], [23], [23], [23], [23], [23], [23], [23], [23], [23], [23], [23], [23], [23], [23], [23], [23]]


    <mike
-- 
Mike Meyer <mwm at mired.org>		http://www.mired.org/consulting.html
Independent Network/Unix/Perforce consultant, email for more information.



More information about the Python-list mailing list