List Slicing :
Slicing helps in creating a new list from an existing list.
Syntax list_name [start:end:step]
Suppose you have a list of Avengers, arranged in the order of your
preference.
avengers=[“Iron Man”,”Thor”,”Hulk”,”Spider Man”,”Captain
America”,”Black Panther”,”Hawk Eye”,”Vision”,”Black Widow”]
Later you decide to split them into a separate list like
favourite=[“Iron Man”,”Thor”,”Hulk”]
less_favourite =[”Spider Man”,”Captain America”,”Black Panther”]
least_favourite=[”Hawk Eye”,”Vision”,”Black Widow”]
Now, we have 3 lists formed from the main list.
Would you want to create these lists again from the beginning?
This is where list slicing helps us.
Here is the code to Get the last few elements of a list.
code to Get the first few elements of a list.
code to Get the numbers within a range.
code to Get elements within a range using the step.
Creating the list of our favorite avengers in the order of preference.
Note: Below slicing will work only if the original list contains 9
elements
Creating a list of favorite avengers from it and print it. (assuming the first 3 are the most favorites)
Creating another list of avengers who are less favorite than the
above. (assuming the middle 3)
Create a list of least favorite avengers (last 3)
Creating a list containing every second avenger from the main list.
Printing the main avenger's list in reverse ie from least favorite to most
favorite.
Comments
Post a Comment