Question about order in lists

Gordon McMillan gmcm at hypernet.com
Fri Aug 13 17:57:46 EDT 1999


Thorsten Z÷ller asks:

> Suppose you write a code as follows:
> 
> x = []                                                # empty list
> list1 = [5, 3, 7]                                  # list containing
> any numbers list2 = [8, 6, 3]                                  #
> another list containing any numbers for i in range(len(list1)):
>     x.append(list1[i-1] + list2[i-1])       # [5+8, 3+6, 7+3]
> ...
> x                                                        # print
> resulting list
> 
> I'm trying to achieve that, having two lists of the same lenght
> containig any numbers, each component of the two lists is added to
> his pendant of the other lists (i.e. the first component of list1 is
> added to the first component of list2 etc). The result is saved in
> another list x. But if I run this code, I do not get [13, 9, 19] for
> x, but [10, 13, 9], i.e. the components are in a wrong order now.
> Why does the order change and how can I avoid it?

Interactive is your friend!

>>> x = []
>>> list1 = [5,3,7]
>>> list2 = [8,6,3]
>>> for i in range(len(list1)):
...   print "i is", i
...   print "i-1 is", i-1
...   print "list1[i-1] is", list1[i-1]
...   print "list2[i-1] is", list2[i-1]
...   x.append(list1[i] + list2[i]) #oops, that's the right way!
...
i is 0
i-1 is -1
list1[i-1] is 7
list2[i-1] is 3
i is 1
i-1 is 0
list1[i-1] is 5
list2[i-1] is 8
i is 2
i-1 is 1
list1[i-1] is 3
list2[i-1] is 6
>>> x
[13, 9, 10]
>>>

- Gordon




More information about the Python-list mailing list