1

I have code from a tutorial that does this:

elements = []

for i in range(0, 6):
    print "Adding %d to the list." % i
    # append is a function that lists understand
    elements.append(i)

for i in elements:
    print "Element was: %d" % i

However, if I only want to print from elements[0] to elements[4], how is this achieved?

halfer
  • 19,824
  • 17
  • 99
  • 186
stanigator
  • 10,768
  • 34
  • 94
  • 129

1 Answers1

8

This can be achieved using slicing:

for i in elements[0:5]:
    print "Element was: %d" % i

The end index is not included in the range, so you need to bump it up from 4 to 5.

The starting zero can be omitted:

for i in elements[:5]:
    print "Element was: %d" % i

For more information, see Explain Python's slice notation

Community
  • 1
  • 1
NPE
  • 486,780
  • 108
  • 951
  • 1,012