Don't forget to also checkout my second blog containing articles to all other related ICT topics!!

Wednesday, May 9, 2012

Python iterables: extracting elements by index

Python offers a pretty powerful way to extract specific items from an iterable.
letters = "abcdefghijklmnopqrstuvwxyz"
print letters[0::2] #from index 0  till end, step by 2
print letters[1::2] #from index 1  till end, step by 2
print letters[3:5]  #from index 3  till 5 (excl)
print letters[10:]  #from index 10 till end
print letters[-1]   #print last letter

acegikmoqsuwy
bdfhjlnprtvxz
de
klmnopqrstuvwxyz
z

numbers = range(15)  #excluding 15
print numbers [0::2] #from index 0  till end, step by 2
print numbers [1::2] #from index 1  till end, step by 2
print numbers [3:5]  #from index 3  till 5 (excl)
print numbers [10:]  #from index 10 till end
print numbers [-1]   #print last letter
[0, 2, 4, 6, 8, 10, 12, 14]
[1, 3, 5, 7, 9, 11, 13]
[3, 4]
[10, 11, 12, 13, 14]
14

No comments:

Post a Comment