How to Get Sublist from List in Python: Simple Guide
In Python, you can get a sublist from a list using
list[start:end] slicing syntax, where start is the index to begin and end is the index to stop (not including end). This returns a new list containing elements from start up to but not including end.Syntax
The syntax to get a sublist from a list uses slicing: list[start:end].
- start: The index where the sublist starts (inclusive). If omitted, it starts from the beginning.
- end: The index where the sublist ends (exclusive). If omitted, it goes to the end of the list.
This creates a new list with elements from start up to but not including end.
python
sublist = my_list[start:end]
Example
This example shows how to get a sublist from a list of numbers using slicing.
python
my_list = [10, 20, 30, 40, 50, 60] sublist = my_list[1:4] print(sublist)
Output
[20, 30, 40]
Common Pitfalls
Common mistakes include:
- Using an
endindex that is out of range (Python handles this gracefully by stopping at the list end). - Forgetting that the
endindex is exclusive, so the element atendis not included. - Using negative indices incorrectly (negative indices count from the end).
python
my_list = [1, 2, 3, 4, 5] # Wrong: expecting to include element at index 3 sublist_wrong = my_list[1:3] # This excludes index 3 # Right: sublist_right = my_list[1:4] # Includes element at index 3 print(sublist_wrong) # Output: [2, 3] print(sublist_right) # Output: [2, 3, 4]
Output
[2, 3]
[2, 3, 4]
Quick Reference
Summary tips for slicing lists:
list[start:end]: Gets elements fromstarttoend - 1.list[:end]: Gets elements from start toend - 1.list[start:]: Gets elements fromstartto the end.list[-n:]: Gets lastnelements.- Negative indices count from the end of the list.
Key Takeaways
Use list slicing syntax list[start:end] to get a sublist in Python.
The start index is inclusive; the end index is exclusive.
Omitting start or end defaults to the beginning or end of the list respectively.
Negative indices count from the end of the list.
Python slicing handles out-of-range indices gracefully without errors.