Sorting numbers in python

Python: How to Sort a List (Strings / Numbers)

Python sorting functionality offers robust features to do basic sorting or customize ordering at a granular level.

In this Article, you’ll learn how to sort various types of data in different data structures, customize the order, and work with two different methods of sorting in Python.

Using sort() Function

In Python, List has a native function to sort its items — sort() function. It can be used in different use-cases to sort the list. It is a very powerful function and can do custom sorting too by providing lambda function.

  • The sort() function modifies the list in-place, therefore the list itself is modified and the function has no return value.
  • It is a method of the *list *class and therefore can only be used with lists.
  • By default, it sorts in ascending order
Читайте также:  Logger in java spring

Sort List containing numbers (Integers and decimals)

Let’s review an example of sorting a list containing numbers. Sorting integers is quite simple as it compares using comparison operator and sorts accordingly.

Numbers = [1,32,8.4,5] Numbers.sort() print(Numbers) #[1,5,8.4,32]

Make sure all items are numbers since number and string cannot be compared via comparison operator »

Sort List containing strings

The sort() function can also be used to sort strings and it is quite robust as it not only compares first character, but subsequent characters if previous ones are same.

Let’s review one simple example:

Flowers = ["rose", "lotus", "lily", "sunflower"] Flowers.sort() print(Flowers) #['lily', 'lotus', 'rose', 'sunflower']

What if you want to compare only specific index in strings? That complex huh?

Let’s try to sort 3 phrases by 2nd character in third word of each phrase!

phrases = [ 'Barking Up The Wrong Tree' ,'Give a Man a Fish', 'A Fool and His Money are Soon Parted' ] phrases.sort(key=lambda x: x.split()[2][1]) phrases # ['Give a Man a Fish', 'Barking Up The Wrong Tree', 'A Fool and His Money are Soon Parted']

Here, we are using key parameter of sort function and providing a lambda function to extract 2nd character of 3rd word in each phrase and use it to sort the list. Pretty clever!

When sorting strings, you also need to pay attention to case since when sorting, sort() method sorts character using ASCII character, therefore Uppercase characters comes before lowercase in sorting.

Flowers = ["rose", "lotus", "lily", "Sunflower"] Flowers.sort() print(Flowers) #['Sunflower', 'lily', 'lotus', 'rose']

Sort list in reverse order using sort()

As sort() orders the list in ascending order by default, if you want to sort the list in descending order, you need to provide the order state as parameter.

Let’s see how we can sort the list in descending order:

Numbers = [1,32,8.4,5] Numbers.sort(reverse=True) print(Numbers) #[32, 8.4, 5, 1]

Using sorted() Function

Python also provides built-in function sorted() to sort all types of iterable data types like — lists, tuples, sets etc.

The sorted() and sort() are kind of similar with few differences. Therefore, either of them can be used to sort the list. We already talked about sort() function, so let’s talk about sorted().

  • The sorted() method does not sort the list in-place. Therefore, it does not modify the list itself rather it returns new sorted list.
  • It is a built-in method in python thus can be used on any kind of iterable variable including lists, tuples and sets
  • By default, it sorts in ascending order

Sort Numbers using sorted()

Just like sort() function, we can sort numbers list using sorted() as well.

Numbers = [1,32,8.4,5] sortednumbers = sorted(Numbers) print(sortednumbers) #[1,5,8.4,32]

Similarly, you can sort list of strings as well using sorted() function.

Sort List with a key argument

Just like with sort() method, you can use key argument to customize sort logic when sorting a list.

Let’s try sorting the list of strings by length of the strings from smallest to biggest string:

Flowers = ["rose", "lotus", "lily", "sunflower"] sortedlist = sorted(Flowers, key=len) print(Flowers) # ['rose', 'lily', 'lotus', 'sunflower']

Two things to note in above example:

  1. We are passing len function to key parameter, therefore sorting function gets length of each string using len function and compares length of each string.
  2. The strings ‘rose‘ comes before ‘lily‘. Why? Since, we are sorting only by length, sorting function won’t change the order if length of strings are same. Therefore, ‘rose‘ and ‘lily‘ would remain as it is. In normal sorting, ‘lily‘ would come before ‘rose‘ in ascending order.

Useful Tip:

As we talked above, sorting list contained strings with both uppercase and lowercase is problematic. How to fix that?

Sort list containing both uppercase and lowercase strings

Remember, both sort() and sorted() function allows us to customize sorting functionality using key parameter.

Thus, we will use key argument, and will lowercase all strings before sorting them using str.lower function.

Not to worry about data mutation as key argument won’t actually modify our strings.

stringlist = ["rose", "lotus", "lily", "Sunflower"] sortedlist = sorted(stringlist) print(sortedlist) # ['Sunflower', 'lily', 'lotus', 'rose'] ==> OOPS # Let's fix it stringlist = ["rose", "lotus", "lily", "Sunflower"] sortedlist = sorted(stringlist, key=str.lower) print(sortedlist) # ['lily', 'lotus', 'rose', 'Sunflower']

Источник

Python List sort() — How to Sort a List in Python (Examples)

In Python, a list is a commonly used data type to store values in the same place for easy access. Sorting a list in turn is one of the most common necessities when handling lists of values.

This guide teaches you how to sort a list in Python. After reading this guide, you know how to sort lists of strings, numbers, objects, and much more.

Here is a quick cheat sheet for sorting numbers and strings in Python. If you’re in a hurry, you may find these useful:

numbers = [5, 3, 9, 2, 1, 3, 4] names = ["Bob", "Charlie", "David", "Alice"] # Sort in increasing order: inc_nums = sorted(numbers) # Sort in decreasing order: dec_nums = sorted(numbers, reverse=True) # Sort alphabetically alpha_names = sorted(names) # Sort in reversed alphabetic order: rev_alpha_names = sorted(names, reverse=True)

Sorting a List in Python

There are two ways to sort a list in Python:

  1. Sort a list directly by calling sort() method of a list.
  2. Create a sorted copy of a list by calling sorted() function on a list.

How to Sort a List of Strings in Python

Sorting a list of strings in Python

When sorting a list of strings, there are two main cases you need to learn:

  1. How to sort a list of strings alphabetically.
  2. How to sort a list of strings in reversed alphabetic order.

The best way to learn how to do this is by seeing some examples.

Example 1: Sort a List of Strings Alphabetically

To sort a list of strings alphabetically, you can simply call the built-in sorted() method on the list of strings. This sorts the strings alphabetically by default.

names = ["Bob", "Charlie", "David", "Alice"] sorted_names = sorted(names) print(sorted_names)

Example 2: Sort a List of Strings In Reverse Alphabetic Order

To sort a list of strings in reverse alphabetic order, you need to set the reverse flag to True in the sorted() function call.

names = ["Bob", "Charlie", "David", "Alice"] sorted_names = sorted(names, reverse=True) print(sorted_names)

How to Sort a List of Numbers in Python

Sorting a list of numbers in Python

One of the most common tasks when it comes to sorting a list is sorting a list of numbers.

There are two main cases you need to learn:

  1. How to sort a list of numbers in increasing order.
  2. How to sort a list of numbers in decreasing order.

Example 1: Sort a List of Numbers in Increasing Order

To sort a list of numbers in Python in increasing order, just call the sorted() method on a list of numbers. This method defaults to sorting the numbers in increasing order.

numbers = [5, 3, 9, 2, 1, 3, 4] sorted_numbers = sorted(numbers) print(sorted_numbers)

Example 2: Sort a List of Numbers in Decreasing Order

To sort a list of numbers in decreasing order, call sorted() and set reverse to True.

numbers = [5, 3, 9, 2, 1, 3, 4] sorted_numbers = sorted(numbers, reverse=True) print(sorted_numbers)

How to Sort a List of Python Objects

Now you know the very basics of sorting a list in Python.

The next fairly common task to do is to sort a list of objects by specific criteria.

Sorting a list of numbers or strings is “easy” because you are probably looking to sort in increasing order or in alphabetic order.

But when it comes to sorting a list of objects, things get a bit trickier. This is because you need to let Python know what you even mean by sorting objects. You need to choose if you want to sort by some particular property or such.

To sort a list of objects, you need to specify the sort method with a key that specifies the sorting criterion. A common way to specify the key is by using a lambda function.

I think the best way to learn how to sort objects is by seeing an example.

For instance, let’s create a very basic class Fruit with properties weight and name.

class Fruit: def __init__(self, weight, name): self.weight = weight self.name = name

Next, let’s create a list of Fruit objects:

banana = Fruit(1, "Banana") orange = Fruit(0.25, "Orange") apple = Fruit(0.5, "Apple") fruits = [banana, apple, orange]

Let’s sort this list of Fruit objects by their weight. To do this, you need to specify key for the sort method, which acts as a sorting criterion.

fruits.sort(key=lambda fruit: fruit.weight)

If you are unfamiliar with the lambda expression above, make sure to read my complete guide to lambdas in Python.

The above lambda expression is just a function that takes a Fruit object and returns its weight. The sort() method uses this function to sort the objects behind the scenes.

Now let’s print the fruits to see that the sorting indeed took place:

for fruit in fruits: print(fruit.name, fruit.weight)
Orange 0.25 Apple 0.5 Banana 1

Yay! As you can tell, now the fruits are sorted by their weight in increasing order. Make sure to play with the example.

For your convenience, here is the full code for the above example:

class Fruit: def __init__(self, weight, name): self.weight = weight self.name = name banana = Fruit(1, "Banana") orange = Fruit(0.25, "Orange") apple = Fruit(0.5, "Apple") fruits = [banana, apple, orange] fruits.sort(key=lambda fruit: fruit.weight) for fruit in fruits: print(fruit.name, fruit.weight)
Orange 0.25 Apple 0.5 Banana 1

How to Sort a List of Dates in Python

Sorting a list of dates in Python

Dealing with dates in Python is common. Sometimes you may have a list of dates you need to sort.

Sorting dates sounds tricky, but it’s actually not.

To sort a list of dates, all you need to do is call the sort() method on the list of date objects.

import datetime dates = [datetime.date(2021, 1, 3), datetime.date(2021, 1, 1), datetime.date(2021, 1, 2)] dates.sort() print(dates)
[datetime.date(2021, 1, 1), datetime.date(2021, 1, 2), datetime.date(2021, 1, 3)]

How to Sort a List of Tuples in Python

Sorting a list of tuples that represent 2D coordinates in Python

Tuple is one of the most popular data types in Python. A tuple is an immutable collection of values.

It’s not rare to have tuples stored in a list. Besides, you might need to sort the list of tuples based on a particular criterion.

The only “tricky” part in sorting tuples is you need to choose the element by which you want to sort the tuples.

  1. Choose the index of the element based on which you want to sort the list of tuples.
  2. Callsorted() on the list of tuples.

For example, let’s sort a list of tuples that represents 2D coordinate pairs:

# (x, y) coordinate pairs locations = [ (0, 2), (5, 1), (3, 9), (1, 6) ] # Sort locations based on the y coordinate. sorted_locations = sorted(locations, key=lambda location: location[1]) print(sorted_locations)

Conclusion

Today you learned how to sort a list in Python in common situations, such as how to sort a list of objects or strings.

To take home, there are two ways to sort a list in Python:

Sometimes you need to specify a criterion function based on which the sorting takes place. To do this, specify the key attribute of the sorting method. Usually, this is a lambda function.

Thanks for reading. I hope you find it useful.

Further Reading

Источник

Оцените статью