In this Python Tuples article we want to learn about How to Sort and Search Python Tuples, we already know that Tuples are immutable Python data structures that contains a collection of elements. they are similar to lists but have some differences such as the fact that they cannot be modified once created. one important use case for tuples is to store related data that should not change such as coordinates or settings for a program.
Sorting and searching tuples is common task in Python programming. in this tutorial we want to talk the different ways to sort and search tuples in Python.
Sort Python Tuples
Python provides several builtin functions to sort tuples such as sorted() and sort(). sorted() function returns new sorted list from an iterable while the sort() method sorts the list in place.
This is an example of how to sort a tuple using the sorted() function:
1 2 3 |
t = (4, 1, 3, 2) sorted_t = sorted(t) print(sorted_t) |
This will be the result
And this is an example of how to sort a tuple using the sort() method:
1 2 3 |
t = [4, 1, 3, 2] t.sort() print(t) |
Note that the sort() method only works for lists not tuples so we first need to convert the tuple to list before sorting.
If the tuple contains nested elements we can use the key parameter to specify a function to extract a value for sorting. for example if we have a tuple of names and ages we can sort the tuple by age:
1 2 3 |
t = [("GeeksCoders", 25), ("Bob", 30), ("John", 20)] sorted_t = sorted(t, key=lambda x: x[1]) print(sorted_t) |
In this example we have used a lambda function to extract the second element of each tuple for sorting.
This will be the result
Search Python Tuples
Searching tuples involves finding specific element or set of elements that matches certain condition. Python provides several ways to search tuples such as using loops or list comprehension.
This is an example of how to search a tuple using loop, in this example we loop through the elements of the tuple and check if any of them match the search condition. if we find a match, we print Found and exit the loop using the break statement. if we don’t find a match we print Not found.
1 2 3 4 5 6 7 |
t = (4, 1, 3, 2) for elem in t: if elem == 3: print("Found") break else: print("Not found") |
We can also use list comprehension to search tuples, so in this example we want to find all event numbers.
1 2 3 |
t = (4, 1, 3, 2) even_numbers = [elem for elem in t if elem % 2 == 0] print(even_numbers) |
This will be the result