pingul
pingul

Reputation: 3473

Using enumerate in a list expression gives unexpected result

I'm playing around with list expressions. This works:

>> l = [1, 4, 3, 4, 5]
>> z = [v for i, v in enumerate(l[0:-1]) if v < l[i + 1]]
>> print(z)
[1, 3, 4]

But this does not:

>> l = [1, 4, 3, 4, 5]
>> z = [v for i, v in enumerate(l[1:-1]) if v < l[i + 1]] # Changed from l[0:-1] -> l[1:-1]
>> print(z)
[] # It should print [3, 4]

They look almost identical -- what am I missing? Removing if v < l[i + 1] in the second expression returns the sublist l[1:-1] as expected.

Upvotes: 0

Views: 56

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1123500

enumerate() starts the count at 0 every time. You shortened l at the start by one element, but the i counter doesn't start at 1, it still starts at 0.

Pass in a start value as the second argument:

>>> [v for i, v in enumerate(l[1:-1], 1) if v < l[i + 1]]
[3, 4]

Upvotes: 3

Related Questions