Detailed Explanation of Python List Sorting

  • 2021-12-05 06:49:17
  • OfStack

In Python, there are two ways to sort lists.

One is to call the sort () method, which returns no value and sorts the list itself in ascending order.


cars = ['bmw', 'audi', 'toyota', 'subaru']
cars.sort()
print(cars)

Output:

['audi', 'bmw', 'subaru', 'toyota']

Another method is to use the sorted () function, which returns an ascending list without affecting the original list.


cars = ['bmw', 'audi', 'toyota', 'subaru']

print("Here is the original list:")
print(cars)

print("\nHere is the sorted list:")
print(sorted(cars))

print("\nHere is the original list again:")
print(cars)

Output:


Here is the original list:
['bmw', 'audi', 'toyota', 'subaru']

Here is the sorted list:
['audi', 'bmw', 'subaru', 'toyota']

Here is the original list again:
['bmw', 'audi', 'toyota', 'subaru']

Summarize

This article is here, I hope to give you help, but also hope that you can pay more attention to this site more content!


Related articles: