How to Sort Lists in Python


This article will train you the way to type a listing in Python.

In Python, you’ll be able to use the type() way to type a listing in position. Or you’ll be able to use the built-in taken care of() serve as to get a taken care of reproduction of the listing.

In this instructional, you’ll be told:

  • Syntax of the type() way and the taken care of() serve as
  • Code examples of sorting lists in ascending and descending order
  • Customize type the use of the key parameter
  • Difference between type() vs taken care of()

Let’s get started!👩🏽‍💻

Syntax of Python type() Method

The type() way acts on a Python listing. And it varieties the listing in position—and modifies the unique listing.

The syntax for Python’s type() way is:

<listing>.type(opposite = True | False, key = <func>)

Let’s now parse the above syntax.

  • <listing> is any legitimate Python listing object.
  • opposite is an not obligatory parameter that takes both True or False.
  • The default cost of opposite is False, and the listing is taken care of in ascending order. Give True to type the listing in descending order.
  • key may be an not obligatory parameter that’s set to <func>.
  • <func> is usually a built-in serve as or a user-defined serve as.

In the following segment, you’ll get started coding easy examples.

How to Sort Python List in Ascending Order

Consider the listing nums. To type the listing in ascending order, you’ll be able to name the type() way at the listing.

▶ Run the next code snippet.

nums = [25,13,6,17,9]
nums.type()
print(nums)

# Output: [6, 9, 13, 17, 25]

The listing nums has been taken care of in ascending order, and the unique listing has been changed. This is named in-place sorting.

How to Sort Python List in Descending Order

To type the listing in descending order, set opposite to True, as proven beneath.

nums = [25,13,6,17,9]
nums.type(opposite = True)
print(nums)

# Output: [25, 17, 13, 9, 6]

You can see that the listing is now taken care of in descending order.

How to Use key with Python type() Method

In this segment, let’s use the key parameter and customise the type.

Here, mod5() is a serve as that takes in a host x, and returns the rest when the quantity x is split by means of 5.

def mod5(x):
  go back x % 5 

And we’d like to use the above serve as because the key.

Now, run the next code cellular.

nums = [25,13,6,17,9]
nums.type(key = mod5)
print(nums)

# Output: [25, 6, 17, 13, 9]

Take a minute to parse the output.

Notice how as an alternative of the common sorting, you at the moment are customizing your type in accordance to the key which is mod5.

  • The quantity that leaves the minimal the rest when divided by means of 5 comes first now.
  • And the quantity that leaves the biggest the rest when divided by means of 5 is the closing component in the taken care of listing.

To check that is the case, run the next code snippet.

nums = [25,13,6,17,9]

for num in nums:
  print(f"num leaves the rest numpercent5 when divided by means of 5")

# Output
25 leaves the rest 0 when divided by means of 5
13 leaves the rest 3 when divided by means of 5
6 leaves the rest 1 when divided by means of 5
17 leaves the rest 2 when divided by means of 5
9 leaves the rest 4 when divided by means of 5

5 divides 25 precisely, and the rest is 0. So that’s the primary component in the taken care of listing. 6 leaves a the rest 1, so it’s the second one component, and so forth. 9 leaves the rest 4 when divided by means of 5, and it’s the closing component in the taken care of listing.

Instead of defining a separate serve as, you may as smartly use lambda functions. In Python, lambdas are one-line nameless purposes. lambda args : expression returns the expression computed at the args.

Now, let’s rewrite the above type the use of the lambda expression, as proven beneath.

nums = [25,13,6,17,9]
nums.type(key = lambda x:xpercent5)
print(nums)

# Output: [25, 6, 17, 13, 9]

So a ways, you’ve discovered how to type a listing of numbers. Next, let’s see how you’ll be able to type a listing of strings in Python.

How to Sort Python List in Alphabetical Order

In this segment, you’ll be told to type a listing of strings—with examples impressed by means of Harry Potter. ✨

python-sort-list

In our instance, scholars is a listing of scholars at Hogwarts. And we’d like to type them in the alphabetical order in their names.

When sorting a listing of strings, the default sorting is in alphabetical order.

scholars = ["Harry","Ron","Hermione","Draco","Cedric"]

Let’s print out the taken care of listing to check the results of sorting.

scholars.type()
print(scholars)

# Output
['Cedric','Draco', 'Harry', 'Hermione', 'Ron']

How to Sort Python List in Reverse Alphabetical Order

In order to type the listing in opposite alphabetical order, set opposite = True, as proven in the code snippet beneath.

scholars.type(opposite = True)
print(scholars)

# Output
['Ron', 'Hermione', 'Harry', 'Draco', 'Cedric']

From the output, you’ll be able to see that the listing has certainly been taken care of in opposite order.

How to Use key Parameter Customize Sort

In this segment, let’s customise the type the use of the not obligatory key parameter.

Consider the next listing, homes.

homes = [
            1:"Draco","house":"Slytherin",
            2:"Harry","house":"Gryffindor",
            3:"Cedric","house":"Hufflepuff"
         ]

Here, homes is a listing of dictionaries. Each dictionary comprises two key-value pairs, one denoting the scholars’ names and the opposite the home to which they belong.

Now, we would love to type this listing homes in the alphabetical order of homes they belong to.

As you’ll have guessed by means of now, we will have to set the key parameter to the home of the actual scholars.

In order to retrieve the home of every scholar, you’ll be able to outline a serve as returnHouse(), as proven beneath.

def returnHouse(scholar):
  go back scholar['house']

This serve as returns the home to which the specific scholar belongs.

Now, you’ll be able to name the type() way at the homes listing, as proven.

homes.type(key=returnHouse)

In the output beneath, understand how the listing is taken care of by means of the home and no longer the scholars’ names. That’s why we have now Gryffindor, Hufflepuff, and Slytherin—in alphabetical order.

print(homes)

# Output
[2: 'Harry', 'house': 'Gryffindor', 
3: 'Cedric', 'house': 'Hufflepuff', 
1: 'Draco', 'house': 'Slytherin']

To outline the key parameter accordingly, you want to additionally use a lambda serve as. For each and every listing merchandise, this serve as returns the home for that listing merchandise.

▶ Run the next code cellular to check this.

homes.type(key=lambda scholar:scholar["house"])
print(homes)

# Output
[2: 'Harry', 'house': 'Gryffindor', 
3: 'Cedric', 'house': 'Hufflepuff', 
1: 'Draco', 'house': 'Slytherin']

In the entire examples to this point, you’ve used the type() way on a listing. And you currently know that it modifies the unique listing.

What when you’d like to retain the unique listing as it’s however download a taken care of reproduction of the listing?

Well, in Python, you’ll be able to use the taken care of() serve as to do that.

Syntax of Python taken care of() Function

The taken care of() serve as takes in a listing or any assortment because the argument. And it returns a taken care of reproduction of the listing—and the unique listing isn’t changed.

The syntax for Python’s taken care of() serve as is:

<sorted_copy> = taken care of(<listing>, opposite = True | False, key = <func>)

Notice how the syntax could be very equivalent to the type() way we noticed previous.

  • <listing> is any legitimate Python listing object and is a required parameter.
  • opposite and key are not obligatory parameters

Note: Unlike the type() way that acts handiest on lists, taken care of() serve as can be utilized to type any Python iterable, akin to lists, strings, and dictionaries.

How to Sort Python List Using taken care of() Function

#1. In this situation, nums is a listing of numbers.

You can name the taken care of() serve as with nums because the argument. And assign it to the listing sorted_nums1.

nums = [25,13,6,17,9]
sorted_nums1 = taken care of(nums)
print(sorted_nums1)

# Output: [6, 9, 13, 17, 25]

In the output above, you’ll be able to see that nums has been taken care of in ascending order by means of default.

Also, understand that the unique listing nums isn’t changed—as a result of taken care of() returns a brand new listing. This is verified beneath.

print(nums)
 # Output: [25, 13, 6, 17, 9]

#2. Now, set the not obligatory parameter opposite to True and get sorted_nums2.

As proven in the code cellular beneath, sorted_nums2 is a brand new listing with the pieces taken care of in the descending order.

sorted_nums2 = taken care of(nums,opposite = True)
print(sorted_nums2)

# Output: [25, 17, 13, 9, 6]

#3. In this situation, let’s paintings with a listing of strings.

As with the former examples, calling the taken care of() serve as returns a brand new listing. And the pieces are taken care of in alphabetical order.

culmination = ['pears','strawberry','apple','pineapple','blueberry']
sorted_fr1 = taken care of(culmination)
print(sorted_fr1)

# Output:
['apple', 'blueberry', 'pears', 'pineapple', 'strawberry']

#4. Now, let’s customise the type the use of the not obligatory key parameter. Set the key to len. This will type the listing in line with the period of the strings.

Note: In Python, the built-in len() serve as takes in any iterable, akin to lists, string, tuples, and so forth. And it returns the period of the iterable.

The string with the shortest period seems first in the taken care of listing, and the longest string seems on the finish of the taken care of listing.

culmination = ['pear','strawberry','apple','pineapple','blueberry']
sorted_fr2 = taken care of(culmination,key=len)
print(sorted_fr2)

# Output:
['pear', 'apple', 'pineapple', 'blueberry', 'strawberry']

In the output above, pear is the shortest string, and strawberry is the longest string. 

Python type() Method vs. taken care of() Function

So a ways, you’ve discovered how to use the type() way in addition to the taken care of() serve as. In this segment, let’s enumerate the diversities between those two strategies.

Python .type() Method Python taken care of() Function
Sorts the listing in position—modifies the unique listing Returns a brand new taken care of listing
Works handiest with Python lists Works with Python iterables akin to lists, strings, and different collections
Has go back form of None Returns a taken care of reproduction of the iterable

Summing Up 👩‍🏫

I’m hoping you discovered this Python lists instructional useful.

Let’s briefly summarize what we’ve coated.

  • Use listing.type(opposite = True | False, key = <func>) with the not obligatory opposite and key parameters to type a listing in position.
  • Use taken care of(listing, opposite = True | False, key = <func>) to get a taken care of reproduction of the listing.

Now that you just’ve discovered how to type Python lists, find out about listing comprehension in Python. Or you want to as smartly learn the way to maintain recordsdata or paintings with JSON recordsdata in Python.

You might check out the examples given above in the Geekflare Online Python Compiler.

Related Articles

Leave a Reply

Your email address will not be published.

Back to top button