Slicing a List


firstHalf = monthList[ : halfCount] secondHalf = monthList[halfCount : ] wordCount = len(firstHalf) middleStart = wordCount/2 middleHalf = monthList[middleStart : \     middleStart+halfCount]

A slice is a subset of a list. Python provides syntax that enables you to quickly grab specific slices of a list.

A slice can be obtained by referencing the list and specifying two indices (separated by a colon) to reference between instead of a single index number. The first index number represents the item in the list at which to start and the second represents the item in the list at which to end.

Slices are returned as a list type and can be accessed and assigned as you would any other list.

Note

Python enables you to use negative indices to index the end rather than the beginning when grabbing slices. For example, to access the final three items in a list, you would use the indices of -3 and -1.


monthList = ["January", "February", "March",\              "April", "May", "June", "July", \              "August", "September","October",\              "November", "December"] wordCount = len(monthList) halfCount = wordCount/2 #Beginning slice firstHalf = monthList[ : halfCount] print firstHalf #End slice secondHalf = monthList[halfCount : ] print secondHalf #Middle slice wordCount = len(firstHalf) middleStart = wordCount/2 middleHalf = monthList[middleStart : \     middleStart+halfCount] print middleHalf #Negative Indices print monthList[-5 : -1]


slice_list.py

['January', 'February', 'March', 'April', 'May', 'June'] ['July', 'August', 'September', 'October', 'November', 'December'] ['April', 'May', 'June', 'July', 'August', 'September'] ['August', 'September', 'October', 'November']


Output from slice_list.py code



Python Phrasebook(c) Essential Code and Commands
Python Phrasebook
ISBN: 0672329107
EAN: 2147483647
Year: N/A
Pages: 138
Authors: Brad Dayley

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net