Question about order in lists

Donn Cave donn at u.washington.edu
Fri Aug 13 17:35:01 EDT 1999


"Thorsten Zöller" <tzoeller at t-online.de> writes:
| 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?

Because you index the input lists with i-1.  Use list1[i] + list2[i],
and then I think it will work as you want.

range() naturally returns a list that starts with 0, which happens to be
where Python sequences start as well.  When you decrement that initial 0
index, -1 is like len(list1)-1, hence the last shall be first.

	Donn Cave, University Computing Services, University of Washington
	donn at u.washington.edu




More information about the Python-list mailing list