Looping through partial sections of an array

python

Solution

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

Problem

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?

Original source

Related problems