[Tutor] Nesting lists?
Scott Widney
SWidney@ci.las-vegas.nv.us
Fri Apr 25 10:34:01 2003
> > I'd like to have 'an array of arrays'. Yes, yes I know it's not an
> > array in python but a list. What I'd like to do is something to the
> > effect of:
> >
> > data = [data1[], data2[], data3[]]
> >
> > but that just gives me an error. I thought of maybe using a
> > dictionary?
>
> >>> data1 = ['a']
> >>> data2 = ['b']
> >>> data3 = ['c']
> >>> data = []
> >>> data.append(data1)
> >>> data.append(data2)
> >>> data.append(data3)
> >>> data
> [['a'], ['b'], ['c']]
There's a very subtle trap here for the unwary. After entering the above in
the interpreter, try this:
>>> data1 = [1]
>>> data2 = [2]
>>> data3 = [3]
>>> data
[['a'], ['b'], ['c']]
>>> data1
[1]
>>> data2
[2]
>>> data3
[3]
>>>
Previously on this list, Danny Yoo gave a wonderful explanation of why this
happens (including ASCII graphics!). This is not a bug! But it can bite you.
Search the archives if you're interested. Now look at this:
>>> data1 = ['a']
>>> data2 = ['b']
>>> data3 = ['c']
>>> data = []
>>> data.append(data1)
>>> data.append(data2)
>>> data.append(data3)
>>> data
[['a'], ['b'], ['c']]
>>> data1.append(1)
>>> data2.append(2)
>>> data3.append(3)
>>> data
[['a', 1], ['b', 2], ['c', 3]]
>>> data1.pop(0)
'a'
>>> data2.pop(0)
'b'
>>> data3.pop(0)
'c'
>>> data
[[1], [2], [3]]
>>>
Food for thought....
Scott