insertion in lists

Larry Bates lbates at swamisoft.com
Wed Mar 3 17:46:08 EST 2004


l=[]
l.append([])

now l=[[]]  # That is this list contains a single empty list.

l.append([])

now l=[[],[]] # That is this list contains two empty lists.

l[0].append('a')

now l=[['a'],[]]

l[0].append('b')

now l=[['a','b'],[]]

l[0][0]='c'

now l=[['c'],'b'],[]]

You should be able to figure it out from here.

What is interesting is that your list can have arbitrary
elements that may be lists, strings, dictionaries, classes,
etc. and they don't have to have anything in common.

More complex example:

class x:
    pass

l=['test',{'key1':1,'key2':2}, 1.5, [1,2,3,5,6,7,8], x]

Has string at l[0]
Has dictionary at l[1]
Has float at l[2]
Has another list at l[3]
Has a class reference at l[4]

WARNING-Never use 'list' as a variable name (as you did
in your example) , it is a keyword and will get redefined
by the assignment (without warning).

-Larry


"Lupe" <luis_ at iname.com> wrote in message
news:c25bjd$1ollgu$1 at ID-202776.news.uni-berlin.de...
> hi,
>
> I'm trying to have a kind of multi-dimensional list which seems to me to
be
> the best way to have an array of not known extension, at the begining of
> the program.
>
> if I have:
>         element
>
>         list [0]
> and want to have list[0][0]
>                  list[0][1]
>
> how can I insert the element to that list[0][0], for example?
> just to put things clearer, if I wanted to insert the element in list[0] I
> could do list.insert(0,element).
>
> I've tried list[0].insert(0,element) but gives me an error.
>
>
> Luis





More information about the Python-list mailing list