You can use slicing:
for item in some_list[2:]:
# do stuff
This will start at the third element and iterate to the end.
Answer from Björn Pollex on Stack Overflowl = [a, b, c, d]
for x in l
print(x)Can this start at an index other than 0?
Well, you could just use the built-in collections.deque class, which supports "rotating":
>>> from collections import deque
>>> li = deque(['a', 'b', 'c', 'd'])
>>> li.rotate(-1)
>>> li
deque(['b', 'c', 'd', 'a'])
Just in case you really want to have a list as result you can always convert it back again:
>>> list(li)
['b', 'c', 'd', 'a']
You could either do this with slicing:
l2 = [*li[1:], *li[:1]]
for i in l2:
print(i)
Which works for Pythons >= 3.5. For versions prior to that you could use li[1:] + li[:1] or chain(li[1:],li[:1]) with chain from itertools.
Alternatively, using two other helpers from the itertools module you could do:
# call list on it if you need a list object
it = islice(cycle(li), 1, len(li)+1)
for i in it:
print(i)
which doesn't create the extra lists.
You can simply use slicing:
for item in I[1:]:
print(item)
And if you want indexing, use pythonic-style enumerate:
START = 1
for index, item in enumerate(I[START:], START):
print(item, index)
First thing is to remember that python uses zero indexing.
You can iterate throught the list except using the range function to get the indexes of the items you want or slices to get the elements.
What I think is becoming confusing here is that in your example, the values and the indexes are the same so to clarify I'll use this list as example:
I = ['a', 'b', 'c', 'd', 'e']
nI = len(I) # 5
The range function will allow you to iterate through the indexes:
for i in range(1, nI):
print(i)
# Prints:
# 1
# 2
# 3
# 4
If you want to access the values using the range function you should do it like this:
for index in range(1, nI):
i = I[index]
print(i)
# Prints:
# b
# c
# d
# e
You can also use array slicing to do that and you don't even need nI. Array slicing returns a new array with your slice.
The slice is done with the_list_reference[start:end:steps] where all three parameters are optional and:
start is the index of the first to be included in the slice
end is the index of the first element to be excluded from the slice
steps is how many steps for each next index starting from (as expected) the start (if steps is 2 and start with 1 it gets every odd index).
Example:
for i in I[1:]:
print(i)
# Prints:
# b
# c
# d
# e