Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] How to Sort and Return a Python List in One Line?
1
How to Sort and Return a Python List in One Line?

To sort and return a Python list in a single line of code, use the
Code:
sorted(list)
method that returns a new list of sorted elements. It copies only the references to the original elements so the returned list is not a deep but a shallow copy.

[Image: sortandreturn-1024x576.jpg]

Let’s dive into the challenge to learn about more details and alternatives. Everything is not always simple. By studying the different methods that solves this, you’ll become a better coder!

Problem: Given a listof comparable objects such as integers or floats. Is there a way to sort the list and return the sorted list in a single line of Python code?

Example: Say, you’ve got the following list.

Code:
a = [4, 2, 1, 3]

You want to sort this list and return the result in a single line. If you use the
Code:
list.sort()
method, the return value is
Code:
None
:

Code:
print(a.sort()) # None

The return value of the
Code:
list.sort()
method is
Code:
None
, but many coders expect it to be the sorted list. So they’re surprised finding out that their variables contain the
Code:
None
type rather than a sorted list.

However, returning
Code:
None
makes perfect sense for the
Code:
list.sort()
method. Why? Because you call the method on a list objectand it modifies this exact list object. It doesn’t create a new list—there won’t be a new list object in memory.

So, how to sort and return a list in a single line of Python code? As a rule of thumb, there are always multiple ways to accomplish the same thing in Python. Let’s dive into the different ways to accomplish this!

Here’s a quick overview of the methods addressed in this article:

https://repl.it/@finxter/ModestAllMp3?lite=true

Exercise: Change the list to be sorted by adding negative floats. Does it still work?

You’ll now learn more about each of the methods.

Method 1: sorted()

The easiest way to accomplish this task is to call Python’s built-in
Code:
sorted()
function that takes an iterable and returns a new list with sorted elements.

Code:
a = [4, 2, 1, 3] # Method 1: sorted() print(sorted(a))

The
Code:
sorted()
function generates a new sorted list that is put into the
Code:
print()
function that prints the sorted list to the shell. The output is the sorted list:

Code:
[1, 2, 3, 4]

This method is the most Pythonicone. But are there alternatives?

Method 2: list.sort() + Ternary Operator

The
Code:
sorted()
method leaves the original list unchanged. But what if you want to sort the original list and get this original list as an output that you can assign to a variable?

The answer is simple: use a combination of the
Code:
list.sort()
method and the ternary operator!

Code:
a = [4, 2, 1, 3] # Method 2: list.sort() + ternary print(a if a.sort() else a) # [1, 2, 3, 4]

You need to understand two concepts: (1)
Code:
list.sort()
and (2) the ternary operator:

  1. The
    Code:
    list.sort()
    method sorts the list elements in place in an ascending manner. To customize the default sorting behavior, use the optional
    Code:
    key
    argument by passing a functionthat returns a comparable value for each element in the list.

  2. The ternary operator
    Code:
    x if c else y
    consists of three operands
    Code:
    x
    ,
    Code:
    c
    , and
    Code:
    y
    . It returns
    Code:
    x
    if the Boolean expression
    Code:
    c
    evaluates to
    Code:
    True
    . Otherwise, if the expression
    Code:
    c
    evaluates to
    Code:
    False
    , the ternary operator returns the alternative
    Code:
    y
    .

The beautiful thing is that the one-liner
Code:
print(a if a.sort() else a)
modifies the original list and returns it right away. How does it do this?

Explanation: First, the
Code:
a.sort()
method is called to check which “branch” of the ternary operator should be visited. The return value of
Code:
a.sort()
will always be
Code:
None
. The
Code:
None
value is automatically converted to the Boolean
Code:
False
. Thus, the ternary operator always returns the list object referred to by variable
Code:
a
.

Note that the only purpose of the ternary operator is to make sure to call the
Code:
a.sort()
method before returning the value
Code:
a
—to make sure it is sorted!

If you print the original list to the shell, you’ll see that it is now sorted:

Code:
>>> print(a) [1, 2, 3, 4]
Method 3: Combining Multiple Statements in a Single Line with Semicolon

An alternative is chaining the statements with a semicolon
Code:
;
to one-linerize a Python code snippet. This strategy works with flat Python programs without, possible nested, blocks:

Code:
a = [4, 2, 1, 3] # Method 3: semicolon a.sort(); print(a) # [1, 2, 3, 4]

If you need to sort a Python list and print its return value to the shell—for example because you run this command from the command line or terminal—you can use this excellent strategy.

You can learn more about how to one-linerize any Python program in my following video:



Python One-Liners Book

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

[Image: 3D_cover-1024x944.jpg]

Python One-Linerswill 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 tips and tricks, regular expressions, machine learning, core data science topics, and 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 Now!!
Reply

Users browsing this thread:
1 Guest(s)


Forum Jump: