How To Sort Numbers In Python

In Python, sorting numbers entails putting a set of numeric values in ascending or descending order. Python includes a variety of built-in functions and techniques for sorting numerical lists, including sorted(), list.sort(), and numpy.sort().

Sorting may be tweaked by specifying extra arguments such as reverse=True for descending order and key for a custom sorting criterion. Sorting is a commonly used procedure in data analysis, machine learning, and a variety of other applications.

Why sorting of numbers is required

Several reasons necessitate number sorting in Python, including:

  • Data Analysis: Sorting is a fundamental procedure in data analysis that is used to organize and summarize huge datasets. It aids in the identification of trends, patterns, and outliers in data.
  • Searching: Sorting can improve search efficiency by applying binary search algorithms, which can identify the requested item in a sorted list faster.
  • Visualization: Sorting can aid in the creation of relevant visualizations such as histograms, box plots, and scatter plots.
  • Machine Learning: Sorting is frequently used in machine learning applications to preprocess data and extract important characteristics.
  • Performance: Sorting algorithms are a key building element in computer science, and many high-performance applications rely on efficient sorting algorithms to attain peak performance.

How to sort a number in python

There are multiple approaches to sort numbers in Python, some of which are:

  • Using the sorted() function
  • Using the list.sort() method
  • Using the numpy.sort() function
  • Using custom sorting criteria

Approach 1: Using the sorted() function

The sorted() function in Python is a built-in function that may be used to sort any iterable object in ascending order, such as a list, tuple, or string. The sorted() method creates a new sorted list while keeping the old object alone. In this example, we will sort a list of numbers in ascending order using the sorted() method.

# Input list of numbers to be sorted
numbers_list = [12, 35, 1, 10, 34, 1]

# Use sorted() function to sort the numbers in ascending order
sorted_numbers = sorted(numbers_list)

# Output the sorted list
print("Original List:", numbers_list)
print("Sorted List:", sorted_numbers)

Output:

Original List: [12, 35, 1, 10, 34, 1]
Sorted List: [1, 1, 10, 12, 34, 35]

Explanation:

  • We first define a list of numbers called numbers_list.
  • We then call the sorted() function on the list and assign the sorted list to a new variable called sorted_numbers.
  • Finally, we print both the original and sorted lists to compare the results.

Approach 2: Using the list.sort() method

In Python, the list.sort() function may be used to sort a list in place, which implies that the original list is adjusted to become sorted. This technique only works with lists and does not return a new list. In this example, we will sort a list of integers in ascending order using the list.sort() function.

# Input list of numbers to be sorted
numbers_list = [12, 35, 1, 10, 34, 1]

# Use sort() method to sort the numbers in ascending order
numbers_list.sort()

# Output the sorted list
print("Sorted List:", numbers_list)

Output:

Sorted List: [1, 1, 10, 12, 34, 35]

Explanation:

  • We first define a list of numbers called numbers_list.
  • We then call the sort() method on the list, which modifies the original list to become sorted in ascending order.
  • Finally, we print the sorted list.

Approach 3: Using the numpy.sort() function

The NumPy library’s numpy.sort() method in Python is used to sort a NumPy array in ascending order along a specified axis. This method returns a sorted clone of the supplied array, while the original array remains untouched. In this example, we will sort a NumPy array of integers in ascending order using the numpy.sort() method.

import numpy as np

# Input array of numbers to be sorted
numbers_array = np.array([12, 35, 1, 10, 34, 1])

# Use numpy.sort() function to sort the array in ascending order
sorted_numbers = np.sort(numbers_array)

# Output the sorted array
print("Original Array:", numbers_array)
print("Sorted Array:", sorted_numbers)

Output:

Original Array: [12, 35,  1, 10, 34,  1]
Sorted Array: [ 1,  1, 10, 12, 34, 35]

Explanation:

  • We first import the NumPy library and create a NumPy array of numbers called numbers_array.
  • We then call the np.sort() function on the array and assign the sorted array to a new variable called sorted_numbers.
  • Finally, we print both the original and sorted arrays to compare the results.

Approach 4: Using custom sorting criteria

With Python, you can also use custom sorting criteria to sort a list of numbers. This implies that you may define a function to decide the order of the items in the list. In this example, we will sort a list of integers in ascending order by their absolute value.

# Define a function to sort based on the absolute value of each number
def sort_by_absolute_value(num):
    return abs(num)

# Input list of numbers to be sorted
numbers_list = [12, -35, 1, 10, -34, 1]

# Use sorted() function with the custom sorting function to sort the numbers
sorted_numbers = sorted(numbers_list, key=sort_by_absolute_value)

# Output the sorted list
print("Original List:", numbers_list)
print("Sorted List by absolute value:", sorted_numbers)

Output:

Original List: [12, -35, 1, 10, -34, 1]
Sorted List by absolute value: [1, 1, 10, 12, -34, -35]

Explanation:

  • We first define a custom sorting function called sort_by_absolute_value that takes a number and returns its absolute value.
  • We then define a list of numbers called numbers_list.
  • We use the sorted() function with the custom sorting function as the key argument to sort the numbers based on their absolute value.
  • Finally, we print both the original and sorted lists to compare the results.

Best Approach for Sorting Numbers in Python

The sorted() method is the best way for sorting in Python depending on your unique use case needs. Nonetheless, sorted() has some benefits over other sorting methods:

  • Simplicity: The sorted() method is simple to use and needs little code, making it an easy way to sort.
  • Flexibility: In Python, the sorted() method may be used to sort any iterable object, such as lists, tuples, and dictionaries. You may also use a key function or lambda expression to determine the sorting criterion.
  • Stability: Because the sorted() function is a stable sort, it keeps the relative order of equal elements in the sorted output. This is useful if you wish to keep the original order of the input pieces.
  • Safety: The sorted() method generates a new sorted list while leaving the original list alone. This is handy if you want to keep the original order of the input components or if you don’t want to change the original list.

Sample Problems for Sorting Numbers in Python

Question 1: Write a python code for the name and age of members of the family using an input function and sort it with respect to number.

Solution:

  • The code first prompts the user to enter the number of family members and stores the value in the variable num members.
  • An empty list member is created to store the name and age of each family member.
  • A for loop is used to iterate over the range of num members, prompting the user to enter the name and age of each family member and appending a tuple of (name, age) to the members list.
  • The sorted() function is used to sort the members list based on the second element of each tuple (i.e., the age of each family member). The lambda function is used as the sorting key to access the second element of each tuple.
  • The sorted list of family members is then printed out to the console.
# Get the number of family members from the user
num_members = int(input("Enter the number of family members: "))

# Create an empty list to store the member names and ages
members = []

# Get the name and age of each family member from the user
for i in range(num_members):
    name = input("Enter the name of family member {}: ".format(i+1))
    age = int(input("Enter the age of family member {}: ".format(i+1)))
    members.append((name, age))

# Sort the list of members by age
members_sorted = sorted(members, key=lambda x: x[1])

# Print the sorted list of members
print("Sorted list of family members by age:")
for member in members_sorted:
    print("{} - {}".format(member[0], member[1]))

Input:

Enter the number of family members: 4
Enter the name of family member 1: Father
Enter the age of family member 1: 40
Enter the name of family member 2: Mother
Enter the age of family member 2: 35
Enter the name of family member 3: Alice
Enter the age of family member 3: 10
Enter the name of family member 4: Bob
Enter the age of family member 4: 5

Output:

Sorted list of family members by age:
Bob - 5
Alice - 10
Mother - 35
Father - 40

Question 2: Write a python code for the movie, genre, total gross and release year using an input function, and sort it with respect to total gross.

Solution:

  • The code prompts the user to enter the number of movies and stores the value in the variable num_movies.
  • An empty list of movies is created to store the movie data.
  • A for loop is used to iterate over the range of num movies, prompting the user to enter the name, genre, total gross, and release year of each movie. A dictionary is created for each movie, with keys for name, genre, total gross, and release year. The movie dictionary is then appended to the movies list.
  • The sorted() function is used to sort the movies list based on the total gross key of each movie dictionary. The lambda function is used as the sorting key to access the total gross key of each movie dictionary. The reverse=True argument is used to sort the list in descending order (i.e., from highest to lowest total gross).
  • The sorted list of movies is then printed out to the console, formatted as name (genre, release year) – total gross.
# Get the number of movies from the user
num_movies = int(input("Enter the number of movies: "))

# Create an empty list to store the movie data
movies = []

# Get the movie data from the user
for i in range(num_movies):
    movie = {}
    movie['name'] = input("Enter the name of movie {}: ".format(i+1))
    movie['genre'] = input("Enter the genre of movie {}: ".format(i+1))
    movie['total_gross'] = int(input("Enter the total gross of movie {}: ".format(i+1)))
    movie['release_year'] = int(input("Enter the release year of movie {}: ".format(i+1)))
    movies.append(movie)

# Sort the list of movies by total gross
movies_sorted = sorted(movies, key=lambda x: x['total_gross'], reverse=True)

# Print the sorted list of movies
print("Sorted list of movies by total gross:")
for movie in movies_sorted:
    print("{} ({}, {}, {}) - ${:,}".format(movie['name'], movie['genre'], movie['release_year'], movie['total_gross']))

Input::

Enter the number of movies: 3
Enter the name of movie 1: The Avengers
Enter the genre of movie 1: Action
Enter the total gross of movie 1: 1518812988
Enter the release year of movie 1: 2012
Enter the name of movie 2: The Lion King
Enter the genre of movie 2: Animation
Enter the total gross of movie 2: 968483777
Enter the release year of movie 2: 1994
Enter the name of movie 3: Titanic
Enter the genre of movie 3: Drama
Enter the total gross of movie 3: 2208372610
Enter the release year of movie 3: 1997

Output:

Sorted list of movies by total gross:
Titanic (Drama, 1997) - $2,208,372,610
The Avengers (Action, 2012) - $1,518,812,988
The Lion King (Animation, 1994) - $968,483,777

Question 3: Question: Write a Python code for taking the sum of every digit in a number from a number list and sort it in descending order.

Solution:

  • First, we take input from the user for the list of numbers.
  • Then we define a function digit sum that takes a number and returns the sum of every digit in it.
  • We then create a new list sum list and use a for loop to iterate through the original list and calculate the sum of digits for each number using the digit sum function.
  • Finally, we use the list.sort() function to sort the sum list in descending order and print it.
# Taking input from user for list of numbers
num_list = list(map(int, input("Enter the numbers separated by spaces: ").split()))

# Function to calculate the sum of every digit in a number
def digit_sum(n):
    s = 0
    while n > 0:
        s += n % 10
        n //= 10
    return s

# Creating a new list with sum of digits for each number in num_list
sum_list = [digit_sum(n) for n in num_list]

# Sorting sum_list in descending order using list.sort()
sum_list.sort(reverse=True)

# Printing the sorted list
print("Sorted list based on sum of digits: ", sum_list)

Input:

Enter the numbers separated by spaces: 15 4 18 6 20 55 84 

Output:

Sorted list based on sum of digits:  [12, 10, 9, 6, 6, 4, 2]

Question 4:  Write a Python program to take data and its frequency as input and rank the data based on its frequency using the list.sort() function.

Explanation:

  • First, we take input from the user for the data and frequency. The input is taken as a list of tuples, where each tuple represents a data point and its frequency.
  • Then we create a dictionary freq dict from the input list, where each key represents a data point, and its corresponding value is the frequency of that data point.
  • We then create a new list rank list and use a for loop to iterate through the dictionary and create a tuple for each data point containing its frequency and the data point itself.
  • We then use the list.sort() function to sort the rank list in descending order based on the frequency of each data point.
  • Finally, we print the sorted list with the rank of each data point based on its frequency.
# Taking input from user for data and frequency
data_freq = [(input("Enter data: "), int(input("Enter frequency: "))) for i in range(int(input("Enter the number of data points: ")))]

# Creating a dictionary from the input list
freq_dict = dict(data_freq)

# Creating a new list with frequency and data point tuples
rank_list = [(freq_dict[key], key) for key in freq_dict]

# Sorting rank_list in descending order based on frequency
rank_list.sort(reverse=True)

# Printing the sorted list with rank based on frequency
print("Rank\tData\tFrequency")
rank = 1
for freq, data in rank_list:
    print(f"{rank}\t{data}\t{freq}")
    rank += 1

Input:

Enter the number of data points: 5
Enter data: A
Enter frequency: 10
Enter data: B
Enter frequency: 20
Enter data: C
Enter frequency: 5
Enter data: D
Enter frequency: 15
Enter data: E
Enter frequency: 5

Output:

Rank	Data	Frequency
1	B	20
2	D	15
3	A	10
4	C	5
5	E	5

Conclusion:

Number sorting in Python is a vital ability for any coder. It facilitates data modification, analysis, and display. In Python, there are various ways to sort integers, including utilizing built-in functions such as sorted(), list.sort(), and numpy.sort() (). Depending on the exact use situation, each of these functions has distinct advantages and downsides. Custom sorting algorithms can also be built to sort numbers based on certain criteria.

When dealing with huge datasets, the sorting algorithm used can have a major influence on performance, therefore selecting the most efficient approach for the task at hand is critical. As a result, understanding the possible sorting algorithms is critical.

Ultimately, number sorting in Python is a fundamental method that every Python programmer should be familiar with. It is a necessary ability in data manipulation and lays the groundwork for more complex data analysis approaches.