Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looping through partial sections of an array

Tags:

python

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?

like image 831
stanigator Avatar asked Dec 06 '25 07:12

stanigator


1 Answers

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

like image 132
NPE Avatar answered Dec 08 '25 20:12

NPE



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!