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
    'n' 
    >>> w[-2]   # second character from the end
    'o' 
    >>> w[1:3]
    'yt'
    >>> w[2:5]
    'tho' 
    >>> w[:5]   # slice from the beginning
    'pytho' 
    >>> w[2:]   # slice until the end
    'thon'
    >>> w[-3]
    'h' 
    >>> w[-3:]   # negative index can also be used in slicing
    'hon' 
    

Practice

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.

Explore