Question: Given a list of numbers, how would you use slicing to extract a sublist containing only the even numbers?
python_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
18: Get Sub List By Slicing a Python List - 1000+ Python Programs
In order to get a sublist by slicing of a Python List, you can use the slice notation which is a colon (:). It is used to separate the start and end indices of the sublist you want to extract.
Slicing Syntax:
list[start:end:step]
| start | It is the index of the first element that you want to include in the sublist. |
| end | It is a parameter that is used to specify the step size between each element (optional). |
| step | It is the index of the first element that you want to exclude from the sublist. |
Finding the even numbers using slicing
python_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_sublist = python_list[1::2] # step = 2
print(even_sublist)
Some more examples with List Slicing
Let us consider the same list of numbers from 1 to 10 and answer the below questions.
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
- Get a sublist from index 2 to index 6.
print(my_list[2:6]) - Get a sublist from index 2 to index 6 with a step of 2.
print(python_list[2:6:2]) - Get a sublist from index 6 to the end of the list
print(python_list[6:]) - Get a copy of the original list
print(python_list[:])
Provide Feedback For This Article
We take your feedback seriously and use it to improve our content. Thank you for helping us serve you better!
😊 Thanks for your time, your feedback has been registered!
Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!