Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

A Slice of the Pie - How to use slices to retrieve list elements

Python Lists

A Slice of the Pie - How to use slices to retrieve list elements

by  EBGreen  Posted    (Edited  )
I am just learning Python, so when I saw that there were no Pyhton FAQs here, I decided to shamelessly use the FAQs to hold what I learn as I go. Please comment on any misconceptions that I may express.

I like the Pyhton treatment of lists. I was pleasantly suprised to find that strings were implicitly treated as lists. This led me to the discovery of something that replaces Left(), Right(), and Mid() (for anyone familiar with VB) in one fell swoop.

A slice is pretty much exactly what it sounds like, a section of the list. I use a string to demonstrate slices, but the same techniques can be applied to any list(array). Here is the slice demo code:

Code:
teststring = "1234567890"
print "Test String = " + teststring
print

#Get all of the items in the list one at a time as is [:]:
print "All elements in correct order [:]"
for character in teststring[:]:
    print character
print

#Get all of the items in the list one at a time in reverse order [::-1]:
print "All Elements in reverse order [::-1]"
print teststring[::-1]
print

#Get the first 2 elements [0:2]:
print "The firat two elements [0:2]:"
print teststring[0:2]
print

#Get the fifth element [4]:
print "The 5th element [4]:"
print teststring[4]
print

#Every other element starting with the first [::2]:
print "Every other element starting with the first [::2]:"
print teststring[::2]
print

#Every other element starting with the second [1::2]:
print "Every other element starting with the second [1::2]:"
print teststring[1::2]
print

#Just the 4th and 7th element [3:7:3]:
print "Just the 4th and 7th element [3:7:3]:"
print teststring[3:7:3]
print

#The 7th then 4th element [6:2:-3]:
print "The 7th then the 4th element [6:2:-3]:"
print teststring[6:2:-3]
print
Register to rate this FAQ  : BAD 1 2 3 4 5 6 7 8 9 10 GOOD
Please Note: 1 is Bad, 10 is Good :-)

Part and Inventory Search

Back
Top