Use the built-in function enumerate():
for idx, x in enumerate(xs):
print(idx, x)
It is non-Pythonic to manually index via for i in range(len(xs)): x = xs[i] or manually manage an additional state variable.
Check out PEP 279 for more.
Answer from Mike Hordecki on Stack OverflowVideos
Use the built-in function enumerate():
for idx, x in enumerate(xs):
print(idx, x)
It is non-Pythonic to manually index via for i in range(len(xs)): x = xs[i] or manually manage an additional state variable.
Check out PEP 279 for more.
Using a for loop, how do I access the loop index, from 1 to 5 in this case?
Use enumerate to get the index with the element as you iterate:
for index, item in enumerate(items):
print(index, item)
And note that Python's indexes start at zero, so you would get 0 to 4 with the above. If you want the count, 1 to 5, do this:
count = 0 # in case items is empty and you need it after the loop
for count, item in enumerate(items, start=1):
print(count, item)
Unidiomatic control flow
What you are asking for is the Pythonic equivalent of the following, which is the algorithm most programmers of lower-level languages would use:
index = 0 # Python's indexing starts at zero for item in items: # Python's for loops are a "for each" loop print(index, item) index += 1
Or in languages that do not have a for-each loop:
index = 0 while index < len(items): print(index, items[index]) index += 1
or sometimes more commonly (but unidiomatically) found in Python:
for index in range(len(items)): print(index, items[index])
Use the Enumerate Function
Python's enumerate function reduces the visual clutter by hiding the accounting for the indexes, and encapsulating the iterable into another iterable (an enumerate object) that yields a two-item tuple of the index and the item that the original iterable would provide. That looks like this:
for index, item in enumerate(items, start=0): # default is zero
print(index, item)
This code sample is fairly well the canonical example of the difference between code that is idiomatic of Python and code that is not. Idiomatic code is sophisticated (but not complicated) Python, written in the way that it was intended to be used. Idiomatic code is expected by the designers of the language, which means that usually this code is not just more readable, but also more efficient.
Getting a count
Even if you don't need indexes as you go, but you need a count of the iterations (sometimes desirable) you can start with 1 and the final number will be your count.
count = 0 # in case items is empty
for count, item in enumerate(items, start=1): # default is zero
print(item)
print('there were {0} items printed'.format(count))
The count seems to be more what you intend to ask for (as opposed to index) when you said you wanted from 1 to 5.
Breaking it down - a step by step explanation
To break these examples down, say we have a list of items that we want to iterate over with an index:
items = ['a', 'b', 'c', 'd', 'e']
Now we pass this iterable to enumerate, creating an enumerate object:
enumerate_object = enumerate(items) # the enumerate object
We can pull the first item out of this iterable that we would get in a loop with the next function:
iteration = next(enumerate_object) # first iteration from enumerate
print(iteration)
And we see we get a tuple of 0, the first index, and 'a', the first item:
(0, 'a')
we can use what is referred to as "sequence unpacking" to extract the elements from this two-tuple:
index, item = iteration
# 0, 'a' = (0, 'a') # essentially this.
and when we inspect index, we find it refers to the first index, 0, and item refers to the first item, 'a'.
>>> print(index)
0
>>> print(item)
a
Conclusion
- Python indexes start at zero
- To get these indexes from an iterable as you iterate over it, use the enumerate function
- Using enumerate in the idiomatic way (along with tuple unpacking) creates code that is more readable and maintainable:
So do this:
for index, item in enumerate(items, start=0): # Python indexes start at zero
print(index, item)
for i in range(15):
print i #will print out 0..14
for i in range(1, 15):
print i # will print out 1..14
for i in range (a, b, s):
print i # will print a..b-1 counting by s. interestingly if while counting by the step 's' you exceed b, it will stop at the last 'reachable' number, example
for i in range(1, 10, 3):
print i
> 1
> 4
> 7
List Splicing:
a = "hello" # there are 5 characters, so the characters are accessible on indexes 0..4
a[1] = 'e'
a[1:2] = 'e' # because the number after the colon is not reached.
a[x:y] = all characters starting from the character AT index 'x' and ending at the character which is before 'y'
a[x:] = all characters starting from x and to the end of the string
In the future, if you ever wonder what the behavior of python is like, you can try it out in the python shell. just type python in the terminal and you can enter any lines you want (though this is mostly convenient for one-liners rather than scripts).
The best way to clarify such doubts is to play with the REPL:
>>> range(10)
range(0, 10)
>>> list(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> x = list(range(10))
>>> x[:3]
[0, 1, 2]
>>> x[:1]
[0]
>>> x[1:10]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Numpy slicing allows you to input a list of indices to an array so that you can slice to the exact values you want.
For example:
import numpy as np
a = np.random.randn(10)
a[[2,4,6,8]]
This will return the 2nd, 4th, 6th, and 8th array elements (keeping in mind that python indices start from 0). So, if you want every 2nd element starting from an index x, you can simply populate a list with those elements and then feed that list into the array to get the elements you want, e.g:
idx = list(range(2,10,2))
a[idx]
This again returns the desired elements (index 2,4,6,8).
Your x is an array of length 20
x = np.arange(0,20)
Returns
x [ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19]
Access every nth(even indices here) element ignoring first two and last two indices in the array x by
print(x[2:len(x)-1:2])
Returns
[2 4 6 8]
And for the rest in similar fashion,
print(x[5:len(x)-1:5])
print(x[4:len(x)-1:4])
Returns
[ 5 10 15]
[ 4 8 12 16]
Hi all,
As I understand it, i could be any variable, but does anyone know why it seems to usually be i for this?
Many thanks in advance :)