Python - Go through list without last element

mark0004 picture mark0004 · Nov 15, 2014 · Viewed 16.9k times · Source

I have a list of tuples and want to create a new list. The elements of the new list are calculated with the last element of the new list (first element is 0) and the the second element of the next tuple of the old list.

To understand better:

list_of_tuples = [(3, 4), (5, 2), (9, 1)]  # old list
new_list = [0]
for i, (a, b) in enumerate(list_of_tuples):
  new_list.append(new_list[i] + b)

So this is the solution, but the last element of the new list does not have to be calculated. So the last element is not wanted.

Is there a pretty way of creating the new list? My solution so far is with range, but does not look that nice:

for i in range(len(list_of_tuples)-1):
  new_list.append(new_list[i] + list_of_tuples[i][1])

I'm new to python, so any help is appreciated.

Answer

user2555451 picture user2555451 · Nov 15, 2014

You can simply use slice notation to skip the last element:

for i, (a, b) in enumerate(list_of_tuples[:-1]):

Below is a demonstration:

>>> lst = [1, 2, 3, 4, 5]
>>> lst[:-1]
[1, 2, 3, 4]
>>> for i in lst[:-1]:
...     i
...
1
2
3
4
>>>