-1

Possible Duplicate:
good primer for python slice notation

I have this Python code; items is a list of tuples:

# Print the first 20
for item in items[:20]:
    print item[0], item[1]

It prints the first twenty elements of the list. If the list has fewer than twenty elements, it still works, but I don't understand why. How do I interpret it?

Community
  • 1
  • 1
vaichidrewar
  • 9,251
  • 18
  • 72
  • 86
  • I was confused by the : at the end which is acting as the start of for loop – vaichidrewar Aug 07 '11 at 22:07
  • @vaichidrewar the first part when omitted means the start, 0. – BrainStorm Aug 07 '11 at 22:09
  • `items[:20]` is a *slice*, as [described elsewhere on SO](http://stackoverflow.com/questions/509211/good-primer-for-python-slice-notation). Essentially, this takes *up to* the first twenty items of the list, ensuring that even if there are not enough items, the slice will not fail with an exception. – li.davidm Aug 07 '11 at 22:05

1 Answers1

4

If the passed value exceeds the number of list elements, slice is limited by the length of the list.

l = range(1,2)
l[:10] == l
eugene_che
  • 1,997
  • 12
  • 12