Go to: Na-Rae Han's home page  

Python 2.7 Tutorial

With Videos by mybringback.com

#9: List Slicing

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

Get Started

Video Summary

  • Different parts of myList were printed out in this script. The shell session includes the script outputs and some interactive portion.
  • 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 extend 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' 
    

Explore