Prev: Constructing lists | Next: List of lists
slice = alist[[start]:[end]:[step]]
where: start
' is the index of the first element of the original list to be included in the sliceend
' is the index of the last element (NOT included in the slice)step
' is the step for moving from start to end valueL1 = [i for i in range(ord('A'), ord('K'))]
print(L1)
L2 = L1[0:5]
L2
spam = ['a','b','c','d','e']
spam2 = spam[2:5]
spam2
L1 = [2*i for i in range(-5,5)]
print(L1)
L2 = L1[:5] # Note that ':' must be included to denote slicing instead of simple indexing
L2
L1 = [i+2 for i in range(-5,5)]
print(L1,'\t',len(L1),'\n')
L2 = L1[5:]
print(L2)
print('The same:',L1[5:10])
L1 = [x for x in range(10)]
print(L1)
L2 = L1[3:10:2] # Note that the element with index '10' is NOT included in L2 slice
L2
L1 = [x for x in range(10)]
L3 = L1[10:2:-3]
L3
L1 = [x for x in range(10)]
L4 = L1[:]
L4
L1 = [x for x in range(10)]
L5 = L1[::2]
L5
L1 = [x for x in range(10)]
L6 = L1[::-1]
L6
L1 = [k for k in range(10)]
print(L1)
L2 = L1[-5:-1]
L2
L1 = [k for k in range(10)]
L3 = L1[-1:-len(L1):-1]
L3
L0 = [x for x in range(1,12)]
L1 = [2*k for k in range(11)]
print(L0,'\t', L1)
L2 = [L1[-i::-1] for i in L0]
L2
L1 = [1,2,3,4,5,6,7,8,9,10]
L1[0:3] = [101, 102, 103] # Values 1,2,3 are replaced by 101, 102, 103
L1
L1 = [1,2,3,4,5,6,7,8,9,10]
L1[0:3] = [101, 102, 103, 104, 105] # Values 1,2,3 are replaced and 104, 105 are inserted
L1
L1 = [1,2,3,4,5,6,7,8,9,10]
L1[0:3] = [101,102] # Values 1,2 are replaced but 3 is deleted
L1
L1 = [1,2,3,4,5,6,7,8,9,10]
L1[0:3] = [] # Values 1,2,3 are now simply deleted
L1
L1 = [1,2,3,4,5,6,7,8,9,10]
L1[1:1] = [101] # Insertion point [1,1] is before element with index [1]
# The value 101 is inserted
L1
L1 = [1,2,3,4,5,6,7,8,9,10]
L1[0:0] = [101,102] # Values 101,102 are inserted in the beginning
L1 # What if we write: L1[:] = [101,102] - Why?
L1 = [1,2,3,4,5,6,7,8,9,10]
L1[len(L1):] = [11, 12, 13] # Extending the list with new values
L1
See a table summarizing Python indexes and slices here
. Free learning material
. See full copyright and disclaimer notice