Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Go through list without last element

Tags:

People also ask

How do I exclude the last element in a list?

pop() function. The simplest approach is to use the list's pop([i]) function, which removes an element present at the specified position in the list. If we don't specify any index, pop() removes and returns the last element in the list.

How do I remove the last 3 elements from a list in Python?

The pop() method will remove the last element from the list, So to remove the last k elements from the Python List, we need to perform the pop() operation k times.

How do you remove the first and last element from a list in Python?

To remove the first element of a Python list, you can use the list. pop(0) method. To remove the last element of a Python list, you can use the list. pop() method without argument.


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.