In this Python article we want to talk about How to Manipulate Python Lists with Slicing & Indexing, so we already know that Python lists are powerful data structure in Python that allow us to store and manipulate collections of items. one of the the best features of lists is the ability to access and manipulate individual elements using slicing and indexing.
Basically slicing and indexing are two closely related operations that allows you to extract parts of the list or modify its contents. in this we will explore how to use slicing and indexing to manipulate Python lists.
How to Manipulate Python Lists with Slicing & Indexing
So first of all let’s talk about Python List Indexing, indexing is the process of accessing specific element of a list by its position or index. in Python list indices start at 0 which means that the first element of a list has index 0, second element has index 1 and so on. for accessing an element of a list by its index you simply need to use square brackets and index number. for example:
1 2 3 4 |
languages = ['Python', 'Java', 'C#', 'C++'] print(languages[0]) print(languages[1]) print(languages[-1]) |
In the above example we have defined list of languages and then we have used indexing to access first, second and last elements of the list.
Note that you can also use negative indices to access elements from the end of the list where -1 refers to the last element, -2 refers to the second-last element, and so on.
If you run the code this will be the result
Let’s talk about Python List Slicing, slicing is the process of extracting subset of elements from a list based on their position or index. in Python you can slice list by using a colon (:) inside square brackets with the start and end indices separated by a colon. for example:
1 2 3 4 |
languages = ['Python', 'Java', 'C#', 'C++'] print(languages[1:3]) print(languages[:2]) print(languages[2:]) |
In the above example we have used slicing to extract subset of elements from the language list. expression languages[1:3] extracts the elements from index 1 to index 2 excluding index 3. expression languages[:2] extracts the elements from beginning of the list up to index 2 excluding index 2. and finally expression languages[2:] extracts the elements from index 2 to the end of the list.
Run the code and this is the result
Indexing and slicing not only allows you to access elements of a list but also you can modify them in place.
1 2 3 4 5 6 |
languages = ['Python', 'Java', 'C#', 'C++'] languages[1] = 'Newone' print(languages) languages[1:3] = ['changes', 'changes2'] print(languages) |
This is the result