Blog Archive

Wednesday, June 20, 2012

List Slicing


 

 

 

 

 

 

 

 

 

 

 

 

 

Slicing Single Dimension Lists:

 
numbers=[1,2,3,4,5,6]

#get 1 by index
print numbers[1]
#get 6 by backward index
print numbers[-1]
>>>
2
6

#slice from beginning to 2
print numbers[:2]
print numbers[0:2]
>>>
[1, 2]
[1, 2]

#slice from index 3 to end
print numbers[3:]
print numbers[3:6]
>>>
[4, 5, 6]
[4, 5, 6]


#slice numbers between index 2 and 6 
print numbers[2:5]
>>>
[3, 4, 5]

#slice list elements in steps of two
print numbers[::2]
#slice list elements 0-4 in steps of two
print numbers[0:4:2]
>>>
[1, 3, 5]
[1, 3]

Slicing Multi-Dimension Lists:

letters=[['a','b','c'],['d','e','f'],['g','h','i']]

#slice 'a' out in row 0 and column 0
print letters[0][0]
>>> 
a

#slice row 1
print letters[1]
>>> 
['d', 'e', 'f']

#slice column 0
for row in letters:
   print row[0]
>>>
a
d
g

No comments:

Post a Comment