How to Sort and Search Python Tuples

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:

 

 

This will be the result

How to Sort and Search Python Tuples
How to Sort and Search Python Tuples

 

 

And this is an example of how to sort a tuple using the sort() method:

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:

In this example we have used a lambda function to extract the second element of each tuple for sorting.

 

This will be the result

How to Sort and Search Python Tuples
How to Sort and Search Python Tuples

 

 

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.

 

 

We can also use list comprehension to search tuples, so in this example we want to find all event numbers.

 

 

This will be the result

Python Search Tuple
Python Search Tuple

 

 

Learn More on Python Tuples

Leave a Comment