List indexing and slicing

List and tuple elements have index numbers. Indexing and slicing operations on lists and tuples work mostly the same way that they do with strings. Here's a quick review of how index numbers work. For more about indexing and slicing, see Chapter 6.

• Working from left to right, the first element has the index 0, the next has the index 1, and so on.

This example shows the items at index 0 and 1 of the list x.

'apple'

'banana'

• Working from right to left, the first element has the index -1, the next one -2, and so on—but the leftmost element is still 0.

This example shows the items at index -1 and -2.

>>> x[-1] 'pear' >>> x[-2] 'banana'

• The beginnings and ends of slices sit between the elements, like notebook dividers.

This example shows that slice 0:1 contains just one element.

Was this article helpful?

0 0

Post a comment