Create an account


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 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.

How to Sort and Return a Python List in One Line?https://blog.finxter.com/wp-content/uplo...00x169.jpg 300w, https://blog.finxter.com/wp-content/uplo...68x432.jpg 768w, https://blog.finxter.com/wp-content/uplo...150x84.jpg 150w" sizes="(max-width: 768px) 100vw, 768px" />

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 list of 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.

a = [4, 2, 1, 3]

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

print(a.sort())
# None

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

However, returning None makes perfect sense for the list.sort() method. Why? Because you call the method on a list object and 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:

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 sorted() function that takes an iterable and returns a new list with sorted elements.

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

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

[1, 2, 3, 4]

This method is the most Pythonic one. But are there alternatives?

Method 2: list.sort() + Ternary Operator


The 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 list.sort() method and the ternary operator!

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) list.sort() and (2) the ternary operator:

  1. The list.sort() method sorts the list elements in place in an ascending manner. To customize the default sorting behavior, use the optional key argument by passing a function that returns a comparable value for each element in the list.
  2. The ternary operator x if c else y consists of three operands x, c, and y. It returns x if the Boolean expression c evaluates to True. Otherwise, if the expression c evaluates to False, the ternary operator returns the alternative y.

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

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

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

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

>>> 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 ; to one-linerize a Python code snippet. This strategy works with flat Python programs without, possible nested, blocks:

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.

Python One-Liners

Python One-Liners will 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!!



https://www.sickgaming.net/blog/2020/09/...-one-line/
Reply



Possibly Related Threads…
Thread Author Replies Views Last Post
  [Tut] How To Kill A Thread In Python? xSicKxBot 0 4 4 hours ago
Last Post: xSicKxBot
  [Tut] Python’s NameError: name ‘xxx’ is not defined — How to Fix This Stupid Bug? xSicKxBot 0 11 10-16-2020, 10:30 PM
Last Post: xSicKxBot
  [Tut] Python IndentationError: unexpected indent (How to Fix This Stupid Bug) xSicKxBot 0 18 10-10-2020, 08:24 PM
Last Post: xSicKxBot
  [Tut] Yield Keyword in Python – A Simple Illustrated Guide xSicKxBot 0 18 10-09-2020, 06:13 PM
Last Post: xSicKxBot
  [Tut] Python Reverse List with Slicing — An Illustrated Guide xSicKxBot 0 29 10-02-2020, 04:24 AM
Last Post: xSicKxBot
  [Tut] How to Remove Duplicates From a Python List While Preserving Order? xSicKxBot 0 31 10-01-2020, 02:21 AM
Last Post: xSicKxBot
  [Tut] How To Update A Key In A Dictionary In Python If The Key Doesn’t Exist? xSicKxBot 0 34 09-29-2020, 09:02 PM
Last Post: xSicKxBot
  [Tut] How to Get the Last Element of a Python List? xSicKxBot 0 36 09-28-2020, 02:36 AM
Last Post: xSicKxBot
  [Tut] List Changes After Assignment — How to Clone or Copy It? xSicKxBot 0 35 09-27-2020, 12:14 AM
Last Post: xSicKxBot
  [Tut] How To Format A String That Contains Curly Braces In Python? xSicKxBot 0 31 09-25-2020, 07:51 PM
Last Post: xSicKxBot

Forum Jump:

Become a Patron!
[-]
Upcoming Events

[-]
Latest Threads
[Tut] How To Kill A Thread In Python?
Last Post: xSicKxBot
Today 05:40 AM
» Replies: 0
» Views: 4
(Indie Deal) FREE Ghost Sweeper, ? NBA 2...
Last Post: xSicKxBot
Today 05:40 AM
» Replies: 0
» Views: 4
News - Nintendo Is Permanently Reducing ...
Last Post: xSicKxBot
Today 04:13 AM
» Replies: 0
» Views: 3
News - Blade Runner: Enhanced Edition De...
Last Post: xSicKxBot
Today 04:13 AM
» Replies: 0
» Views: 5
Humble Ultimate Fantasy Game Development...
Last Post: xSicKxBot
Yesterday 10:00 PM
» Replies: 0
» Views: 7
Microsoft - Honeywell teams up with Micr...
Last Post: xSicKxBot
Yesterday 09:59 PM
» Replies: 0
» Views: 6
Fedora - Secure NTP with NTS
Last Post: xSicKxBot
Yesterday 09:59 PM
» Replies: 0
» Views: 6
News - Video: First 4 Figures Unboxes It...
Last Post: xSicKxBot
Yesterday 09:59 PM
» Replies: 0
» Views: 6
News - Battlefield 5 Definitive Edition ...
Last Post: xSicKxBot
Yesterday 09:59 PM
» Replies: 0
» Views: 7
(Indie Deal) Alien Cat Bundle, RIDE 4 re...
Last Post: xSicKxBot
Yesterday 05:21 PM
» Replies: 0
» Views: 6

[-]
Twitter

[-]
Sponsored
Get the Deal of the Week at RefurBees.com

Copyright © SickGaming.net 2012-2020