Slicing in python list || New way to learn python list in 2023

Slicing in python list

Slicing in python list
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’ ]

[ ‘Green’, ‘Yellow’, ‘Black’, ‘Blue’ ]
 
[ ‘Black’ ]
 

Slicing of python list with more examples:-

In color_lost[ 2 : 5 ], If we remove the first number the list will print from the beginning, and if we remove the second number list will print till the end.
 

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[  :  ] )

Output
 
[ ‘Red’, ‘Green’, ‘Yellow’, ‘Black’, ‘Blue’, ‘White’ ]
 

Important Links: Informatics Practices

If you like my post please share it with your friends by simply clicking the below social media button, and Don’t forget to comment so we will update ourselves.

Share in a Single Click

Leave a Reply

Your email address will not be published. Required fields are marked *