Go to: Na-Rae Han's home page  

Python 3 Notes

        [ HOME | LING 1330/2330 ]

Tutorial 8: List Slicing

<< Previous Tutorial           Next Tutorial >>
On this page: slice indexing with [:], negative indexing, slice and negative indexing on strings.

Video Tutorial

Python 3 Changes

print(x,y) instead of print x, y

Video Summary

  • It's possible to "slice" a list in Python. This will return a specific segment of a given list. For example, the command myList[2] will return the 3rd item in your list (remember that Python begins counting with the number 0).
  • You can expand the length and change the location of the list segment returned using a colon in your command. Ex: myList[2:5] will return the 3rd through 5th items in your list. Typing myList[:5] will return every item up to the 5th item on a list, while myList[2:] on the other hand, with a colon following the numeral, will return every item starting with the 3rd.
  • Python can also return a segment of a list counting from the end. This is done simply by inserting a negative before the desired numerals within the slice command. Ex: myList[-5] will return your fifth from last entry.

Learn More

  • As in the previous tutorial, the same negative indexing and slicing mechanism extends to strings. Below, various substrings in the string 'python' are returned.
    >>> w = 'python'
    >>> w[-1]   # first character from the end
    >>> w[-2]   # second character from the end
    >>> w[1:3]
    >>> w[2:5]
    >>> w[:5]   # slice from the beginning
    >>> w[2:]   # slice until the end
    >>> w[-3]
    >>> w[-3:]   # negative index can also be used in slicing


The list is fox = ['the', 'quick', 'brown', 'fox', 'jumps', 'over']. How do you get ['quick', 'brown', 'fox'] from this list, using slicing? Try in IDLE shell.

Using slicing, how can you get 'dental' from 'incidentally'? How about 'action' from 'traction'? Try in IDLE shell.