5

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?

SuperBiasedMan
  • 9,814
  • 10
  • 45
  • 73
Bhavik Joshi
  • 2,557
  • 6
  • 24
  • 48

5 Answers5

9

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

Community
  • 1
  • 1
Indradhanush Gupta
  • 4,067
  • 10
  • 44
  • 60
  • Since OP doesn't know about slicing he might not know you can do something similar using range or xrange if you're using 2.7. Just something else to think about – SirParselot Sep 09 '15 at 13:48
6

Code:

array=['for','loop','in','python']
for arr in array[2:]:
    print arr

Output:

in
python
The6thSense
  • 8,103
  • 8
  • 31
  • 65
wolendranh
  • 4,202
  • 1
  • 28
  • 37
2

See Python slicing:

for arr in array[2:]:
    print arr
Delgan
  • 18,571
  • 11
  • 90
  • 141
2

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
The6thSense
  • 8,103
  • 8
  • 31
  • 65
2

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.

Thomas B.
  • 2,276
  • 15
  • 24