CodeGym /Courses /Python SELF EN /Getting Sublists

Getting Sublists

Python SELF EN
Level 7 , Lesson 3
Available

3.1 Index Range

Getting a sublist from a list is a common task, tackled using the slicing mechanism. Slices let you extract elements from a list by specifying the starting and ending indices of the range, as well as the step at which to extract elements.

Using slices

You can get a slice of a list using the syntax list[start:stop:step], where:

  • start — starting index of the element (inclusive);
  • stop — ending index of the element (exclusive);
  • step — step with which elements are selected.

Slice syntax allows you to specify the start and end indices of the list you want to extract. Remember, Python uses zero-based indexing, so the first element has index 0, and the third has index 2.


my_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

# Get a sublist from the third to the seventh element 
sub_list = my_list[2:7]
print(sub_list)  # [2, 3, 4, 5, 6]
            
# Get every second element of the list
step_list = my_list[0:10:2]
print(step_list)  # [0, 2, 4, 6, 8]

If start isn't specified, it defaults to the beginning of the list, and if stop isn't specified, it defaults to the end of the list. If step isn't specified, it defaults to 1.

Examples:


my_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

# From the start up to the third element 
sub_list = my_list[:3]
print(sub_list)  # [0, 1, 2]
            
# From the first element/index to the end
step_list = my_list[1:]
print(step_list)  # [1, 2, 3, 4, 5, 6, 7, 8, 9]

3.2 Negative Indices

In Python, negative indices provide a powerful way to work with lists, allowing you to reference elements from the end of the list. This is especially useful for getting sublists without knowing the exact length of the original list.

Negative indices in Python start with -1, which corresponds to the last element of the list. -2 will point to the second-to-last element, and so on. Using negative indices makes it easier to access elements from the end of the list without needing to calculate their position from the start.

Usage examples

Suppose you have a list:


my_list = ['a', 'b', 'c', 'd', 'e']

To get the last three elements, you can use a slice with negative indices:


sub_list = my_list[-3:]
print(sub_list)  # Outputs ['c', 'd', 'e']

If you need to get a sublist between certain elements starting from the end, you can combine negative and positive indices:


sub_list = my_list[-4:3]
print(sub_list)  # Outputs ['b', 'c']

You can even reverse the list

By using the step parameter, you can create more complex slices, like reversing the list:


sub_list = my_list[::-1]
print(sub_list)  # Outputs ['e', 'd', 'c', 'b', 'a'] 

Benefits of using negative indices:

  • Simplify code: Accessing elements from the end of the list becomes intuitive and doesn't require additional calculations.
  • Flexibility: This approach works with any list, regardless of its size.
  • Readability: The code becomes easier to read and understand, especially when working with the last elements of a list.

Negative indices are a powerful tool in a Python programmer's arsenal, allowing effective and concise management of sublists, improving code readability and flexibility.

3.3 Is the Element in the List?

Checking if an element exists in a list is often used for controlling data flow and program logic. In Python, you can do this using the in operator, which returns True if the element is in the list and False otherwise.

Using the in Operator

The in operator is a simple and intuitive way to check for an element's presence:


my_list = [1, 2, 3, 4, 5]
element = 3
exists = element in my_list
print(exists)  # Outputs True 

Usage in Conditional Statements

The in operator is often used in conditional statements, such as:


my_list = ["apple", "banana", "cherry"] 
element = "apple"
            
if element in my_list:
    print("The element is in the list.")
else:
    print("Element not found.")

Useful! Searching for an element with in is efficient for small or medium-sized lists. However, for large datasets or frequent search operations, it might be more efficient to use other data structures like sets (set), which provide faster search times.

2
Task
Python SELF EN, level 7, lesson 3
Locked
Slices
Slices
2
Task
Python SELF EN, level 7, lesson 3
Locked
String Search
String Search
Comments (2)
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION
Gurjinder Level 10
22 March 2025
Please change the image in 3.2 to english
22 May 2025
Still they haven't LOL