INTELLIGENT WORK FORUMS
FOR COMPUTER PROFESSIONALS
Come Join Us!
Are you a
Computer / IT professional?
Join Tek-Tips now!
- Talk With Other Members
- Be Notified Of Responses
To Your Posts
- Keyword Search
- One-Click Access To Your
- Automated Signatures
On Your Posts
- Best Of All, It's Free!
*Tek-Tips's functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.
Partner With Us!
"Best Of Breed" Forums Add Stickiness To Your Site
(Download This Button Today!)
"...This is easily the most helpful website I've ever used, and this is the best forum with the quickest response time bar none...."
Where in the world do Tek-Tips members come from?
A Slice of the Pie - How to use slices to retrieve list elements
Posted: 25 Aug 05 (Edited 25 Aug 05)
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:
teststring = "1234567890"
print "Test String = " + teststring
#Get all of the items in the list one at a time as is [:]:
print "All elements in correct order [:]"
for character in teststring[:]:
#Get all of the items in the list one at a time in reverse order [::-1]:
print "All Elements in reverse order [::-1]"
#Get the first 2 elements [0:2]:
print "The firat two elements [0:2]:"
#Get the fifth element :
print "The 5th element :"
#Every other element starting with the first [::2]:
print "Every other element starting with the first [::2]:"
#Every other element starting with the second [1::2]:
print "Every other element starting with the second [1::2]:"
#Just the 4th and 7th element [3:7:3]:
print "Just the 4th and 7th element [3:7:3]:"
#The 7th then 4th element [6:2:-3]:
print "The 7th then the 4th element [6:2:-3]:"
Back to Python FAQ Index
Back to Python Forum
Join Tek-Tips® Today!
Join your peers on the Internet's largest technical computer professional community.
It's easy to join and it's free.
Here's Why Members Love Tek-Tips Forums:
- Talk To Other Members
- Notification Of Responses To Questions
- Favorite Forums One Click Access
- Keyword Search Of All Posts, And More...
Register now while it's still free!
Already a member? Close this window and log in.
Join Us Close