One frequently finds expressions of this type in python questions on SO. Either for just accessing all items of the iterable
for i in range(len(a)): print(a[i])
Which is just a clumbersome way of writing:
for e in a: print(e)
Or for assigning to elements of the iterable:
for i in range(len(a)): a[i] = a[i] * 2
Which should be the same as:
for i, e in enumerate(a): a[i] = e * 2 # Or if it isn't too expensive to create a new iterable a = [e * 2 for e in a]
Or for filtering over the indices:
for i in range(len(a)): if i % 2 == 1: continue print(a[i])
Which could be expressed like this:
for e in a [::2]: print(e)
Or when you just need the length of the list, and not its content:
for _ in range(len(a)): doSomethingUnrelatedToA()
Which could be:
for _ in a: doSomethingUnrelatedToA()
In python we have enumerate
, slicing, filter
, sorted
, etc... As python for
constructs are intended to iterate over iterables and not only ranges of integers, are there real-world use-cases where you need in range(len(a))
?
If we use range(len(gases)) in a for loop, it assigns each index of the list to the loop variable in turn… …so we can print out (index, element) pairs one by one. This is a very common idiom in Python for those cases where we really do want to know each element's location as well as its value.
Why use enumerate() instead of range() in your python's loops. enumerate() is faster when you want to repeatedly access the list/iterable items at their index. When you just want a list of indices, it is faster to use len() and range().
range(len(alist)-1,0,-1) returns a range of integers starting at len(alist) - 1 , continuing utill it hits 0 , and increasing by -1 (decreasing by 1) each iteration.
To find the length of a range in Python, call len() builtin function and pass the range object as argument. len() function returns the number of items in the range.
If you need to work with indices of a sequence, then yes - you use it... eg for the equivalent of numpy.argsort...:
>>> a = [6, 3, 1, 2, 5, 4] >>> sorted(range(len(a)), key=a.__getitem__) [2, 3, 1, 5, 4, 0]
What if you need to access two elements of the list simultaneously?
for i in range(len(a[0:-1])): something_new[i] = a[i] * a[i+1]
You can use this, but it's probably less clear:
for i, _ in enumerate(a[0:-1]): something_new[i] = a[i] * a[i+1]
Personally I'm not 100% happy with either!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With