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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With