Introduction
Python Data Types & Operators
Conditional Statements
Python Loops
Python Strings
Python Lists
Python Tuple
In Python, list indexing allows you to access elements in a list by their position. Here’s a breakdown of how list indexing works:
1. Positive Indexing
- The index starts at
0
for the first element of the list. - Each subsequent element increases the index by
1
.
my_list = ['apple', 'banana', 'cherry', 'date']
print(my_list[0]) # 'apple'
print(my_list[1]) # 'banana'
print(my_list[2]) # 'cherry'
print(my_list[3]) # 'date'
2. Negative Indexing
- Negative indices allow you to access elements from the end of the list.
- The last element is indexed as
-1
, the second-to-last as-2
, and so on.
Example:
my_list = ['apple', 'banana', 'cherry', 'date']
print(my_list[-1]) # 'date' (last element)
print(my_list[-2]) # 'cherry' (second to last)
print(my_list[-3]) # 'banana' (third to last)
print(my_list[-4]) # 'apple' (fourth to last)
3. List Slicing
- You can access a sublist (or slice) using a colon (
:
) inside the square brackets. - Syntax:
list[start:end:step]
Example:
my_list = ['apple', 'banana', 'cherry', 'date', 'elderberry']
print(my_list[1:4]) # ['banana', 'cherry', 'date']
print(my_list[:3]) # ['apple', 'banana', 'cherry']
print(my_list[2:]) # ['cherry', 'date', 'elderberry']
print(my_list[::2]) # ['apple', 'cherry', 'elderberry']