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,484
  • 10
  • 45
  • 70
Bhavik Joshi
  • 2,477
  • 6
  • 22
  • 44

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
  • 3,797
  • 9
  • 41
  • 59
  • 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
  • 7,631
  • 6
  • 30
  • 63
wolendranh
  • 3,994
  • 1
  • 26
  • 37
2

See Python slicing:

for arr in array[2:]:
    print arr
Delgan
  • 16,542
  • 9
  • 83
  • 127
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
  • 7,631
  • 6
  • 30
  • 63
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,226
  • 14
  • 22