# Sort a List, String, Tuple in Python (sort, sorted)

5/5 - (1 vote)

## Basics of Sorting in Python

In Python, sorting data structures like lists, strings, and tuples can be achieved using built-in functions like `sort()` and `sorted()`. These functions enable you to arrange the data in ascending or descending order. This section will provide an overview of how to use these functions.

The `sorted()` function is primarily used when you want to create a new sorted list from an iterable, without modifying the original data. This function can be used with a variety of data types, such as lists, strings, and tuples.

Here’s an example of sorting a list of integers:

```numbers = [5, 8, 2, 3, 1]
sorted_numbers = sorted(numbers)
print(sorted_numbers)  # Output: [1, 2, 3, 5, 8]
```

To sort a string or tuple, you can simply pass it to the `sorted()` function as well:

```text = "python"
sorted_text = sorted(text)
print(sorted_text)  # Output: ['h', 'n', 'o', 'p', 't', 'y']
```

For descending order sorting, use the `reverse=True` argument with the `sorted()` function:

```numbers = [5, 8, 2, 3, 1]
sorted_numbers_desc = sorted(numbers, reverse=True)
print(sorted_numbers_desc)  # Output: [8, 5, 3, 2, 1]
```

On the other hand, the `sort()` method is used when you want to modify the original list in-place. One key point to note is that the `sort()` method can only be called on lists and not on strings or tuples.

To sort a list using the `sort()` method, simply call this method on the list object:

```numbers = [5, 8, 2, 3, 1]
numbers.sort()
print(numbers)  # Output: [1, 2, 3, 5, 8]
```

For descending order sorting using the `sort()` method, pass the `reverse=True` argument:

```numbers = [5, 8, 2, 3, 1]
numbers.sort(reverse=True)
print(numbers)  # Output: [8, 5, 3, 2, 1]
```

Using the `sorted()` function and the `sort()` method, you can easily sort various data structures in Python, such as lists, strings, and tuples, in ascending or descending order.

💡 Recommended: Python List `sort()` – The Ultimate Guide

## Sorting Lists

In Python, sorting a list is a common operation that can be performed using either the `sort()` method or the `sorted()` function. Both these approaches can sort a list in ascending or descending order.

### Using .sort() Method

The `sort()` method is a built-in method of the list object in Python. It sorts the elements of the list in-place, meaning it modifies the original list without creating a new one. By default, the `sort()` method sorts the list in ascending order.

Here’s an example of how to use the `sort()` method to sort a list of numbers:

```numbers = [5, 2, 8, 1, 4]
numbers.sort()
print(numbers)  # Output: [1, 2, 4, 5, 8]
```

To sort the list in descending order, you can pass the `reverse=True` argument to the `sort()` method:

```numbers = [5, 2, 8, 1, 4]
numbers.sort(reverse=True)
print(numbers)  # Output: [8, 5, 4, 2, 1]
```

### Sorting Lists with sorted() Function

The `sorted()` function is another way of sorting a list in Python. Unlike the `sort()` method, the `sorted()` function returns a new sorted list without modifying the original one.

Here’s an example showing how to use the `sorted()` function:

```numbers = [5, 2, 8, 1, 4]
sorted_numbers = sorted(numbers)
print(sorted_numbers)  # Output: [1, 2, 4, 5, 8]
```

Similar to the `sort()` method, you can sort a list in descending order using the `reverse=True` argument:

```numbers = [5, 2, 8, 1, 4]
sorted_numbers = sorted(numbers, reverse=True)
print(sorted_numbers)  # Output: [8, 5, 4, 2, 1]
```

Both the `sort()` method and `sorted()` function allow for sorting lists as per specified sorting criteria. Use them as appropriate depending on whether you want to modify the original list or get a new sorted list.

Check out my video on the `sorted()` function: 👇

💡 Recommended: Python `sorted()` Function

## Sorting Tuples

Tuples are immutable data structures in Python, similar to lists, but they are enclosed within parentheses and cannot be modified once created. Sorting tuples can be achieved using the built-in `sorted()` function.

### Ascending and Descending Order

To sort a tuple or a list of tuples in ascending order, simply pass the tuple to the `sorted()` function.

Here’s an example:

```my_tuple = (3, 1, 4, 5, 2)
sorted_tuple = sorted(my_tuple)
print(sorted_tuple)  # Output: [1, 2, 3, 4, 5]
```

For descending order, use the optional `reverse` argument in the `sorted()` function. Setting it to `True` will sort the elements in descending order:

```my_tuple = (3, 1, 4, 5, 2)
sorted_tuple = sorted(my_tuple, reverse=True)
print(sorted_tuple)  # Output: [5, 4, 3, 2, 1]
```

### Sorting Nested Tuples

When sorting a list of tuples, Python sorts them by the first elements in the tuples, then the second elements, and so on. To effectively sort nested tuples, you can provide a custom sorting key using the `key` argument in the `sorted()` function.

Here’s an example of sorting a list of tuples in ascending order by the second element in each tuple:

```my_list = [(1, 4), (3, 1), (2, 5)]
sorted_list = sorted(my_list, key=lambda x: x[1])
print(sorted_list)  # Output: [(3, 1), (1, 4), (2, 5)]
```

Alternatively, to sort in descending order, simply set the `reverse` argument to `True`:

```my_list = [(1, 4), (3, 1), (2, 5)]
sorted_list = sorted(my_list, key=lambda x: x[1], reverse=True)
print(sorted_list)  # Output: [(2, 5), (1, 4), (3, 1)]
```

As shown, you can manipulate the `sorted()` function through its arguments to sort tuples and lists of tuples with ease. Remember, tuples are immutable, and the `sorted()` function returns a new sorted list rather than modifying the original tuple.

## Sorting Strings

In Python, sorting strings can be done using the `sorted()` function. This function is versatile and can be used to sort strings (`str`) in ascending (alphabetical) or descending (reverse alphabetical) order.

In this section, we’ll explore sorting individual characters in a string and sorting a list of words alphabetically.

### Sorting Characters

To sort the characters of a string, you can pass the string to the `sorted()` function, which will return a list of characters in alphabetical order. Here’s an example:

```text = "python"
sorted_chars = sorted(text)
print(sorted_chars)
```

Output:

```['h', 'n', 'o', 'p', 't', 'y']
```

If you want to obtain the sorted string instead of the list of characters, you can use the `join()` function to concatenate them:

```sorted_string = ''.join(sorted_chars)
print(sorted_string)
```

Output:

```hnopty
```

For sorting the characters in descending order, set the optional `reverse` parameter to `True`:

```sorted_chars_desc = sorted(text, reverse=True)
print(sorted_chars_desc)
```

Output:

```['y', 't', 'p', 'o', 'n', 'h']
```

### Sorting Words Alphabetically

When you have a list of words and want to sort them alphabetically, the `sorted()` function can be applied directly to the list:

```words = ['apple', 'banana', 'kiwi', 'orange']
sorted_words = sorted(words)
print(sorted_words)
```

Output:

```['apple', 'banana', 'kiwi', 'orange']
```

To sort the words in reverse alphabetical order, use the `reverse` parameter again:

```sorted_words_desc = sorted(words, reverse=True)
print(sorted_words_desc)
```

Output:

```['orange', 'kiwi', 'banana', 'apple']
```

## Using Key Parameter

The `key` parameter in Python’s `sort()` and `sorted()` functions allows you to customize the sorting process by specifying a callable to be applied to each element of the list or iterable.

### Sorting with Lambda

Using lambda functions as the `key` argument is a concise way to sort complex data structures. For example, if you have a list of tuples representing names and ages, you can sort by age using a lambda function:

```names_ages = [('Alice', 30), ('Bob', 25), ('Charlie', 35)]
sorted_names_ages = sorted(names_ages, key=lambda x: x[1])
print(sorted_names_ages)
```

Output:

```[('Bob', 25), ('Alice', 30), ('Charlie', 35)]
```

### Using itemgetter from operator Module

An alternative to using lambda functions is the `itemgetter()` function from the `operator` module. The `itemgetter()` function can be used as the `key` parameter to sort by a specific index in complex data structures:

```from operator import itemgetter

names_ages = [('Alice', 30), ('Bob', 25), ('Charlie', 35)]
sorted_names_ages = sorted(names_ages, key=itemgetter(1))
print(sorted_names_ages)
```

Output:

```[('Bob', 25), ('Alice', 30), ('Charlie', 35)]
```

### Sorting with Custom Functions

You can also create custom functions to be used as the `key` parameter. For example, to sort strings based on the number of vowels:

```def count_vowels(s):
return sum(s.count(vowel) for vowel in 'aeiouAEIOU')

words = ['apple', 'banana', 'cherry']
sorted_words = sorted(words, key=count_vowels)
print(sorted_words)
```

Output:

```['apple', 'cherry', 'banana']
```

### Sorting Based on Absolute Value

To sort a list of integers based on their absolute values, you can use the built-in `abs()` function as the `key` parameter:

```numbers = [5, -3, 1, -8, -7]
sorted_numbers = sorted(numbers, key=abs)
print(sorted_numbers)
```

Output:

```[1, -3, 5, -7, -8]
```

### Sorting with cmp_to_key from functools

In some cases, you might need to sort based on a custom comparison function. The `cmp_to_key()` function from the `functools` module can be used to achieve this. For instance, you could create a custom comparison function to sort strings based on their lengths:

```from functools import cmp_to_key

def custom_cmp(a, b):
return len(a) - len(b)

words = ['cat', 'bird', 'fish', 'ant']
sorted_words = sorted(words, key=cmp_to_key(custom_cmp))
print(sorted_words)
```

Output:

```['cat', 'ant', 'bird', 'fish']
```

## Sorting with Reverse Parameter

In Python, you can easily sort lists, strings, and tuples using the built-in functions `sort()` and `sorted()`. One notable feature of these functions is the `reverse` parameter, which allows you to control the sorting order – either in ascending or descending order.

By default, the `sort()` and `sorted()` functions will sort the elements in ascending order. To sort them in descending order, you simply need to set the `reverse` parameter to `True`. Let’s explore this with some examples.

Suppose you have a list of numbers and you want to sort it in descending order. You can use the `sort()` method for lists:

```numbers = [4, 1, 7, 3, 9]
numbers.sort(reverse=True)  # sorts the list in place in descending order
print(numbers)  # Output: [9, 7, 4, 3, 1]
```

If you have a string or a tuple and want to sort in descending order, use the `sorted()` function:

```text = "abracadabra"
sorted_text = sorted(text, reverse=True)
print(sorted_text)  # Output: ['r', 'r', 'd', 'c', 'b', 'b', 'a', 'a', 'a', 'a', 'a']

values = (4, 1, 7, 3, 9)
sorted_values = sorted(values, reverse=True)
print(sorted_values)  # Output:  [9, 7, 4, 3, 1]
```

Keep in mind that the `sort()` method works only on lists, while the `sorted()` function works on any iterable, returning a new sorted list without modifying the original iterable.

When it comes to sorting with custom rules, such as sorting a list of tuples based on a specific element, you can use the `key` parameter in combination with the `reverse` parameter. For example, to sort a list of tuples by the second element in descending order:

```data = [("apple", 5), ("banana", 3), ("orange", 7), ("grape", 2)]
sorted_data = sorted(data, key=lambda tup: tup[1], reverse=True)
print(sorted_data)  # Output: [('orange', 7), ('apple', 5), ('banana', 3), ('grape', 2)]
```

So the `reverse` parameter in Python’s sorting functions provides you with the flexibility to sort data in either ascending or descending order. By combining it with other parameters such as `key`, you can achieve powerful and customized sorting for a variety of data structures.

## Sorting in Locale-Specific Order

Sorting lists, strings, and tuples in Python is a common task, and it often requires locale-awareness to account for language-specific rules. You can sort a list, string or tuple using the built-in `sorted()` function or the `sort()` method of a list. But to sort it in a locale-specific order, you must take into account the locale’s sorting rules and character encoding.

We can achieve locale-specific sorting using the `locale` module in Python. First, you need to import the `locale` library and set the locale using the `setlocale()` function, which takes two arguments, the category and the locale name.

```import locale
locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')  # Set the locale to English (US)
```

Next, use the `locale.strxfrm()` function as the key for the `sorted()` function or the `sort()` method. The `strxfrm()` function transforms a string into a form suitable for locale-aware comparisons, allowing the sorting function to order the strings according to the locale’s rules.

```strings_list = ['apple', 'banana', 'Zebra', 'éclair']
sorted_strings = sorted(strings_list, key=locale.strxfrm)
```

The `sorted_strings` list will now be sorted according to the English (US) locale, with case-insensitive and accent-aware ordering.

Keep in mind that it’s essential to set the correct locale before sorting, as different locales may have different sorting rules. For example, the German locale would handle umlauts differently from English, so setting the locale to `de_DE.UTF-8` would produce a different sorting order.

## Sorting Sets

In Python, sets are unordered collections of unique elements. To sort a set, we must first convert it to a list or tuple, since the `sorted()` function does not work directly on sets. The `sorted()` function returns a new sorted list from the specified iterable, which can be a list, tuple, or set.

```import locale
strings_list = ['apple', 'banana', 'Zebra', 'éclair']
sorted_strings = sorted(strings_list, key=locale.strxfrm)
print(sorted_strings)
# ['Zebra', 'apple', 'banana', 'éclair']```

In this example, we begin with a set named `sample_set` containing four integers. We then use the `sorted()` function to obtain a sorted list named `sorted_list_from_set`. The output will be:

```[1, 2, 4, 9]
```

The `sorted()` function can also accept a `reverse` parameter, which determines whether to sort the output in ascending or descending order. By default, `reverse` is set to `False`, meaning that the output will be sorted in ascending order. To sort the set in descending order, we can set `reverse=True`.

```sorted_list_descending = sorted(sample_set, reverse=True)
print(sorted_list_descending)
```

This code snippet will output the following:

```[9, 4, 2, 1]
```

It’s essential to note that sorting a set using the `sorted()` function does not modify the original set. Instead, it returns a new sorted list, leaving the original set unaltered.

## Sorting by Group and Nested Data Structures

Sorting nested data structures in Python can be achieved using the built-in `sorted()` function or the `.sort()` method. You can sort a list of lists or tuples based on the value of a particular element in the inner item, making it useful for organizing data in groups.

To sort nested data, you can use a `key` argument along with a `lambda` function or the `itemgetter()` method from the `operator` module. This allows you to specify the criteria based on which the list will be sorted.

For instance, suppose you have a list of tuples representing student records, where each tuple contains the student’s name and score:

```students = [("Alice", 85), ("Bob", 78), ("Charlie", 91), ("Diana", 92)]
```

To sort the list by the students’ scores, you can use the `sorted()` function with a lambda function as the key:

```sorted_students = sorted(students, key=lambda student: student[1])
```

This will produce the following sorted list:

```[("Bob", 78), ("Alice", 85), ("Charlie", 91), ("Diana", 92)]
```

Alternatively, you can use the `itemgetter()` method:

```from operator import itemgetter

sorted_students = sorted(students, key=itemgetter(1))
```

This will produce the same result as using the lambda function.

When sorting lists containing nested data structures, consider the following tips:

• Use the `lambda` function or `itemgetter()` for specifying the sorting criteria.
• Remember that `sorted()` creates a new sorted list, while the `.sort()` method modifies the original list in-place.
• You can add the `reverse=True` argument if you want to sort the list in descending order.

## Handling Sorting Errors

When working with sorting functions in Python, you might encounter some common errors such as `TypeError`. In this section, we’ll discuss how to handle such errors and provide solutions to avoid them while sorting lists, strings, and tuples using the `sort()` and `sorted()` functions.

`TypeError` can occur when you’re trying to sort a list that contains elements of different data types. For example, when sorting an unordered list that contains both integers and strings, Python would raise a `TypeError: '<' not supported between instances of 'str' and 'int'` as it cannot compare the two different data types.

Consider this example:

```mixed_list = [3, 'apple', 1, 'banana']
mixed_list.sort()
# Raises: TypeError: '<' not supported between instances of 'str' and 'int'
```

To handle the `TypeError` in this case, you can use error handling techniques such as a `try-except` block. Alternatively, you could also preprocess the list to ensure all elements have a compatible data type before sorting. Here’s an example using a `try-except` block:

```mixed_list = [3, 'apple', 1, 'banana']
try:
mixed_list.sort()
except TypeError:
print("Sorting error occurred due to incompatible data types")
```

Another approach is to sort the list using a custom sorting key in the `sorted()` function that can handle mixed data types. For instance, you can convert all the elements to strings before comparison:

```mixed_list = [3, 'apple', 1, 'banana']
sorted_list = sorted(mixed_list, key=str)
print(sorted_list)  # Output: [1, 3, 'apple', 'banana']
```

With these techniques, you can efficiently handle sorting errors that arise due to different data types within a list, string, or tuple when using the `sort()` and `sorted()` functions in Python.

## Sorting Algorithm Stability

Stability in sorting algorithms refers to the preservation of the relative order of items with equal keys. In other words, when two elements have the same key, their original order in the list should be maintained after sorting. Python offers several sorting techniques, with the most common being `sort()` for lists and `sorted()` for strings, lists, and tuples.

Python’s sorting algorithms are stable, which means that equal keys will have their initial order preserved in the sorted output. For example, consider a list of tuples containing student scores and their names:

```students = [(90, "Alice"), (80, "Bob"), (90, "Carla"), (85, "Diana")]
```

Sorted by scores, the list should maintain the order of students with equal scores as in the original list:

```sorted_students = sorted(students)
# Output: [(80, 'Bob'), (85, 'Diana'), (90, 'Alice'), (90, 'Carla')]
```

Notice that Alice and Carla both have a score of 90 but since Alice appeared earlier in the original list, she comes before Carla in the sorted list as well.

To take full advantage of stability in sorting, the `key` parameter can be used with both `sort()` and `sorted()`. The `key` parameter allows you to specify a custom function or callable to be applied to each element for comparison. For instance, when sorting a list of strings, you can provide a custom function to perform a case-insensitive sort:

```words = ["This", "is", "a", "test", "string", "from", "Andrew"]
sorted_words = sorted(words, key=str.lower)
# Output: ['a', 'Andrew', 'from', 'is', 'string', 'test', 'This']
```

### How to sort a list of tuples in descending order in Python?

To sort a list of tuples in descending order, you can use the `sorted()` function with the `reverse=True` parameter. For example, for a list of tuples `tuples_list`, you can sort them in descending order like this:

```sorted_tuples = sorted(tuples_list, reverse=True)
```

### What is the best way to sort a string alphabetically in Python?

The best way to sort a string alphabetically in Python is to use the `sorted()` function, which returns a sorted list of characters. You can then join them using the `join()` method like this:

```string = "hello"
sorted_string = "".join(sorted(string))
```

### What are the differences between sort() and sorted() in Python?

`sort()` is a method available for lists, and it sorts the list in-place, meaning it modifies the original list. `sorted()` is a built-in function that works with any iterable, returns a new sorted list of elements, and doesn’t modify the original iterable.

```# Using sort()
numbers = [3, 1, 4, 2]
numbers.sort()
print(numbers)  # [1, 2, 3, 4]

# Using sorted()
numbers = (3, 1, 4, 2)
sorted_numbers = sorted(numbers)
print(sorted_numbers)  # [1, 2, 3, 4]
```

### How can you sort a tuple in descending order in Python?

To sort a tuple in descending order, you can use the `sorted()` function with the `reverse=True` parameter, like this:

```tuple_numbers = (3, 1, 4, 2)
sorted_tuple = sorted(tuple_numbers, reverse=True)
```

Keep in mind that this will create a new list. If you want to create a new tuple instead, you can convert the sorted list back to a tuple like this:

```sorted_tuple = tuple(sorted_tuple)
```

### How do you sort a string in Python without using the sort function?

You can sort a string without using the `sort()` function by converting the string to a list of characters, using a list comprehension to sort the characters, and then using the `join()` method to create the sorted string:

```string = "hello"
sorted_list = [char for char in sorted(string)]
sorted_string = "".join(sorted_list)
```

### What is the method to sort a list of strings with numbers in Python?

If you have a list of strings containing numbers and want to sort them based on the numeric value, you can use the `sorted()` function with a custom `key` parameter. For example, to sort a list of strings like `["5", "2", "10", "1"]`, you can do:

```strings_with_numbers = ["5", "2", "10", "1"]
sorted_strings = sorted(strings_with_numbers, key=int)
```

This will sort the list based on the integer values of the strings: `["1", "2", "5", "10"]`.

## Python One-Liners Book: Master the Single Line First!

Python programmers will improve their computer science skills with these useful one-liners.

Python One-Liners will teach you how to read and write “one-liners”: concise statements of useful functionality packed into a single line of code. You’ll learn how to systematically unpack and understand any line of Python code, and write eloquent, powerfully compressed Python like an expert.

The book’s five chapters cover (1) tips and tricks, (2) regular expressions, (3) machine learning, (4) core data science topics, and (5) useful algorithms.

Detailed explanations of one-liners introduce key computer science concepts and boost your coding and analytical skills. You’ll learn about advanced Python features such as list comprehension, slicing, lambda functions, regular expressions, map and reduce functions, and slice assignments.

You’ll also learn how to:

• Leverage data structures to solve real-world problems, like using Boolean indexing to find cities with above-average pollution
• Use NumPy basics such as array, shape, axis, type, broadcasting, advanced indexing, slicing, sorting, searching, aggregating, and statistics
• Calculate basic statistics of multidimensional data arrays and the K-Means algorithms for unsupervised learning
• Create more advanced regular expressions using grouping and named groups, negative lookaheads, escaped characters, whitespaces, character sets (and negative characters sets), and greedy/nongreedy operators
• Understand a wide range of computer science topics, including anagrams, palindromes, supersets, permutations, factorials, prime numbers, Fibonacci numbers, obfuscation, searching, and algorithmic sorting

By the end of the book, you’ll know how to write Python at its most refined, and create concise, beautiful pieces of “Python art” in merely a single line.

Get your Python One-Liners on Amazon!!