I have a list like this:
array=['for','loop','in','python']
for arr in array:
print arr
This will give me the output
for
lop
in
python
I want to print
in
python
How can I skip the first 2 indices in python?
I have a list like this:
array=['for','loop','in','python']
for arr in array:
print arr
This will give me the output
for
lop
in
python
I want to print
in
python
How can I skip the first 2 indices in python?
Use slicing.
array = ['for','loop','in','python']
for arr in array[2:]:
print arr
When you do this, the starting index in the for
loop becomes 2
. Thus the output would be:
in
python
For more info on slicing
read this: Explain Python's slice notation
Code:
array=['for','loop','in','python']
for arr in array[2:]:
print arr
Output:
in
python
If you want to skip other lines or want to try different combination then you could do this
Code:
for i ,j in enumerate(array):
if i not in (1,2):
print j
Output:
for
python
Slicing is good, but if you're considered about performance, you might prefer itertools.islice
:
import itertools
array = 'for loop in python'.split()
for x in itertools.islice(array, 2, None):
print x
because the slice operator builds a completely new list, which means overhead if you just want to iterate over it.