Slicing in python list
Types of Slicing in python list
Slicing in python list means we can get a sub list of any python list using the : operator.
color_list = [ ‘Red’, ‘Green’, ‘Yellow’, ‘Black’, ‘Blue’, ‘White’ ]
print( color_list[ 1 : 4 ] )
Output
[ ‘Green’, ‘Yellow’, ‘Black’ ]
Note :- The only thing we have to remember is that in color_list[ 1 : 4 ], 1 is the index value and 4 is the number of elements in the list from the left. So in the above example, Green is at index 1 and Black is at 4th position.
Examples
color_list = [ ‘Red’, ‘Green’, ‘Yellow’, ‘Black’, ‘Blue’, ‘White’ ]
print( color_list[ 2 : 6 ] )
print( color_list[ 1 : 5 ] )
print( color_list[ 3 : 4 ] )
Output
[ ‘Yellow’, ‘Black’, ‘Blue’, ‘White’ ]
Slicing of python list with more examples:-
color_list = [ ‘Red’, ‘Green’, ‘Yellow’, ‘Black’, ‘Blue’, ‘White’ ]
print( color_list[ : 5 ] )
print( color_list[ 3 : ] )
Output
[ ‘Red’, ‘Green’, ‘Yellow’, ‘Black’, ‘Blue’ ]
[ ‘Black’, ‘Blue’, ‘White’ ]
If we remove both numbers then the list will be copied.
color_list = [ ‘Red’, ‘Green’, ‘Yellow’, ‘Black’, ‘Blue’, ‘White’ ]
print( color_list[ : ] )
Important Links: Informatics Practices
What is Python List
Characteristics of Python List
How to Create Python List
How to Traverse a list in Python
How to Manipulate list in Python
How to Modify multiple elements in Python list
Built in function of Python List