09-09-2020, 04:08 AM
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 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]](https://blog.finxter.com/wp-content/uploads/2020/09/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.
You want to sort this list and return the result in a single line. If you use the method, the return value is :
The return value of the method is , but many coders expect it to be the sorted list. So they’re surprised finding out that their variables contain the type rather than a sorted list.
However, returning makes perfect sense for the 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 function that takes an iterable and returns a new list with sorted elements.
The function generates a new sorted list that is put into the function that prints the sorted list to the shell. The output is the sorted list:
This method is the most Pythonicone. But are there alternatives?
Method 2: list.sort() + Ternary Operator
The 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 method and the ternary operator!
You need to understand two concepts: (1) and (2) the ternary operator:
The beautiful thing is that the one-liner modifies the original list and returns it right away. How does it do this?
Explanation: First, the method is called to check which “branch” of the ternary operator should be visited. The return value of will always be . The value is automatically converted to the Boolean . Thus, the ternary operator always returns the list object referred to by variable .
Note that the only purpose of the ternary operator is to make sure to call the method before returning the value —to make sure it is sorted!
If you print the original list to the shell, you’ll see that it is now sorted:
Method 3: Combining Multiple Statements in a Single Line with Semicolon
An alternative is chaining the statements with a semicolon to one-linerize a Python code snippet. This strategy works with flat Python programs without, possible nested, blocks:
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]](https://blog.finxter.com/wp-content/uploads/2020/06/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!!
To sort and return a Python list in a single line of code, use the
Code:
sorted(list)![[Image: sortandreturn-1024x576.jpg]](https://blog.finxter.com/wp-content/uploads/2020/09/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()Code:
NoneCode:
print(a.sort())
# NoneThe return value of the
Code:
list.sort()Code:
NoneCode:
NoneHowever, returning
Code:
NoneCode:
list.sort()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()Code:
a = [4, 2, 1, 3] # Method 1: sorted()
print(sorted(a))The
Code:
sorted()Code:
print()Code:
[1, 2, 3, 4]This method is the most Pythonicone. But are there alternatives?
Method 2: list.sort() + Ternary Operator
The
Code:
sorted()The answer is simple: use a combination of the
Code:
list.sort()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()- The method sorts the list elements in place in an ascending manner. To customize the default sorting behavior, use the optionalCode:
list.sort()argument by passing a functionthat returns a comparable value for each element in the list.Code:key
- The ternary operator consists of three operandsCode:
x if c else y,Code:x, andCode:c. It returnsCode:yif the Boolean expressionCode:xevaluates toCode:c. Otherwise, if the expressionCode:Trueevaluates toCode:c, the ternary operator returns the alternativeCode:False.Code:y
The beautiful thing is that the one-liner
Code:
print(a if a.sort() else a)Explanation: First, the
Code:
a.sort()Code:
a.sort()Code:
NoneCode:
NoneCode:
FalseCode:
aNote that the only purpose of the ternary operator is to make sure to call the
Code:
a.sort()Code:
aIf you print the original list to the shell, you’ll see that it is now sorted:
Code:
>>> print(a)
[1, 2, 3, 4]An alternative is chaining the statements with a semicolon
Code:
;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]](https://blog.finxter.com/wp-content/uploads/2020/06/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!!

