a = [5, 66, 7, 8, 9, ...]
Is it possible to make an iteration instead of writing like this?
a[1] - a[0]
a[2] - a[1]
a[3] - a[2]
a[4] - a[3]
...
Thank you!
a = [5, 66, 7, 8, 9, ...]
Is it possible to make an iteration instead of writing like this?
a[1] - a[0]
a[2] - a[1]
a[3] - a[2]
a[4] - a[3]
...
Thank you!
for a small list in python 2 or any list in python 3, you can use
for a larger list, you probably want
if you are using python 2
And I would consider writing it as a generator expression instead
This will avoid creating the second list in memory all at once but you will only be able to iterate over it once. If you only want to iterate over it once, then this is ideal and it's easy enough to change if you decide later that you need random or repeated access. In particular if you were going to further process it to make a list, then this last option is ideal.
update:
The fastest method by far is
Here is the example from the itertools reciepes:
Which is not very readable.If you prefer something more understandable and understand how generators work, here a bit longer example with the same result:
Using
range
is perfectly fine. However, programming (like maths) is about building on abstractions. Consecutive pairs [(x0, x1), (x1, x2), ..., (xn-2, xn-1)], are called pairwise combinations, see for example a recipe in the itertools docs. Once you have this function in your toolset, you can write:Or, as a generator expression:
Sure.
I fail to see what the real problem is here. Have you read the python tutorial?