18: Get Sub List By Slicing a Python List - 1000+ Python Programs


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]


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)

[2, 4, 6, 8, 10]



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]

  1. Get a sublist from index 2 to index 6.
    print(my_list[2:6])

    [3,4,5,6]

  2. Get a sublist from index 2 to index 6 with a step of 2.
    print(python_list[2:6:2])

    [3, 5]

  3. Get a sublist from index 6 to the end of the list
    print(python_list[6:])

    [6,7,8,9,10]

  4. Get a copy of the original list
    print(python_list[:])

    [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

-

Facing issues? Have Questions? Post them here! I am happy to answer!


Author Info:

Rakesh (He/Him) is a seasoned developer with over 10 years of experience in web and app development, and a deep knowledge of operating systems. Author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap