Until now, given a list L, i was using range(len(L)) to access its elements:
L = [4, 3, 5, 2, 7]
for i in range(len(L)):
print(i, "-", L[i])
However, I've read that this approach is not pythonic and there's a function called enumerate that can do the work as well:
L = [4, 3, 5, 2, 7]
for i, n in enumerate(L):
print(i, "-", n)
Now, allow me to propose a problem to show the trouble I've been experiencing with this approach:
Given a list of integers
L, transform the list so that every elementnin the resulting list is the sum of the elements up tonin the initial list.
Using the first approach that would be:
L = [4, 3, 5, 2, 7]
for i in range(1, len(L)):
L[i] = L[i] + L[i - 1]
When trying the second approach:
L = [4, 3, 5, 2, 1]
for i, n in enumerate(L): #It starts at element 0!
L[i] = n + L[i - 1]
The questions that result from this problem are the following:
- How can I make enumerate start at element 1?
- Is the second approach actually worth it in this case?
- If the previous answer is "no", when is it worth it?
Answering to
How can I make enumerate start at element 1You do that this way:
L = [4, 3, 5, 2, 1] for i, n in enumerate(L, start=1):