Posted on Leave a comment

Python One Line Ternary

Ternary (from Latin ternarius) is an adjective meaning “composed of three items”. (source) So, literally, the ternary operator in Python is composed of three operands.

Syntax: The three operands are written in an intuitive combination ... if ... else ....

<On True> if <Condition> else <On False>
Operand Description
<On True> The return expression of the operator in case the condition evaluates to True
<Condition> The condition that determines whether to return the <On True> or the <On False> branch.
<On False> The return expression of the operator in case the condition evaluates to False
Operands of the Ternary Operator

Let’s have a look at a minimum example in our interactive code shell:

Exercise: Run the code and input your age. What’s the output? Run the code again and try to change the output!

Let’s dive into the different variants of the Ternary operator in Python!

Python Ternary Examples

Let’s have a quick overview of a few examples on different methods to use the ternary operator:

age = 17 # Method 1: Basic Ternary
print('wtf' if age<20 else 'What?') 'wtf' # Method 2: Ternary Tuple
# (onFalse, onTrue) [condition]
print(('wtf', 'What?') [age<20]) 'What?' # Method 3: Ternary Dictionary
# Use Dictionary True/False values
print({True: 'wtf', False: 'What?'} [age<20]) 'wtf' # Method 4: Ternary Lambda
# Lambda function with 0 arguments
# Execute only one branch expression --> more efficient
print((lambda: 'wtf', lambda:'What?') [age<20]()) 'What?'

Some of them are pretty confusing, right? Stay with me for a moment because you’ll learn about each of those next! 🙂

Python Ternary Tuple

Python Ternary Dictionary

Python Ternary Lambda

Python Ternary Multiple Lines

Python Ternary Elif

Python Ternary Nested

Python Ternary Plot

Python Ternary Diagram

Python Ternary Evaluation Order

Python Ternary Try Except

Python Ternary Tree

Python Ternary in List Comprehension

Python Ternary Pep8 Pythonic

Python Ternary Can’t Assign to Conditional Expression

Python Ternary For Loop

Python Ternary Break

Python Ternary None

Python Ternary Multiple Conditions

Where to Go From Here?

Enough theory, let’s get some practice!

To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

Practice projects is how you sharpen your saw in coding!

Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?

Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!

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

Posted on Leave a comment

Python One Line Quicksort

In this one-liner tutorial, you’ll learn about the popular sorting algorithm Quicksort. Surprisingly, a single line of Python code is all you need to write the Quicksort algorithm!

Problem: Given a list of numerical values (integer or float). Sort the list in a single line of Python code using the popular Quicksort algorithm!

Example: You have list [4, 2, 1, 42, 3]. You want to sort the list in ascending order to obtain the new list [1, 2, 3, 4, 42].

Short answer: The following one-liner solution sorts the list recursively using the Quicksort algorithm:

q = lambda l: q([x for x in l[1:] if x <= l[0]]) + [l[0]] + q([x for x in l if x > l[0]]) if l else []

You can try it yourself using the following interactive code shell:

Now, let’s dive into some details!

A Conceptual Introduction

The following introduction is based on my new book “Python One-Liners” (Amazon Link) that teaches you the power of the single line of code (use it wisely)!

Python One-Liners

Introduction: Quicksort is not only a popular question in many code interviews – asked by Google, Facebook, and Amazon – but also a practical sorting algorithm that is fast, concise, and readable. Because of its beauty, you won’t find many introduction to algorithm classes which don’t discuss the Quicksort algorithm.

Overview: Quicksort sorts a list by recursively dividing the big problem (sorting the list) into smaller problems (sorting two smaller lists) and combining the solutions from the smaller problems in a way that it solves the big problem. In order to solve each smaller problem, the same strategy is used recursively: the smaller problems are divided into even smaller subproblems, solved separately, and combined. Because of this strategy, Quicksort belongs to the class of “Divide and Conquer” algorithms.

Algorithm: The main idea of Quicksort is to select a pivot element and then placing all elements that are larger or equal than the pivot element to the right and all elements that are smaller than the pivot element to the left. Now, you have divided the big problem of sorting the list into two smaller subproblems: sorting the right and the left partition of the list. What you do now is to repeat this procedure recursively until you obtain a list with zero elements. This list is already sorted, so the recursion terminates.

The following Figure shows the Quicksort algorithm in action:

Figure: The Quicksort algorithm selects a pivot element, splits up the list into (i) an unsorted sublist with all elements that are smaller or equal than the pivot, and (ii) an unsorted sublist with all elements that are larger than the pivot. Next, the Quicksort algorithm is called recursively on the two unsorted sublists to sort them. As soon as the sublists contain maximally one element, they are sorted by definition – the recursion ends. At every recursion level, the three sublists (left, pivot, right) are concatenated before the resulting list is handed to the higher recursion level.

This brings us to the following code:

Python One-Liner Quicksort [Code]

Create a function q which implements the Quicksort algorithm in a single line of Python code – and thus sorts any argument given as a list of integers.

## The Data
unsorted = [33, 2, 3, 45, 6, 54, 33] ## The One-Liner
q = lambda l: q([x for x in l[1:] if x <= l[0]]) + [l[0]] + q([x for x in l if x > l[0]]) if l else [] ## The Result
print(q(unsorted))

Listing: One-liner solution for the Quicksort algorithm using recursion.

What is the output of this code? Let’s see…

Explanation Quicksort One-Liner

We have already discussed the recursive Quicksort algorithm above. The one-liner resembles exactly the discussed algorithm. First, we create a new lambda function q which takes only one list argument l.

The lambda function has the following structure:

lambda l: q(left) + pivot + q(right) if l else []

The lambda function returns the empty list [] in the recursion base case (that is – the list to be sorted is empty and, therefore, trivially sorted).

In any other case, it selects the pivot element as the first element of list l, divides all elements into two sublists (left and right) based on whether they are smaller or larger than the pivot. To achieve this, we use simple list comprehension.

As the two sublists are not necessarily sorted, we recursively execute the Quicksort algorithm on them. Finally, we combine all three lists and return the sorted list. Therefore, the result is:

## The Result
print(q(unsorted))
# [2, 3, 6, 33, 33, 45, 54]

Related: For an interactive experience of what you’ve just learned, check out our Instagram post about the Quicksort algorithm:

Related Resources:

Where to Go From Here?

Enough theory, let’s get some practice!

To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

Practice projects is how you sharpen your saw in coding!

Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?

Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!

Posted on Leave a comment

Python One Line X

This is a running document in which I’ll answer all questions regarding the single line of Python code. If you want to check out my book “Python One-Liners” and become a one-liner wizard—be my guest! 😉

Let’s get started!

Python One Line If Without Else

Python One Line If Else

Python One Line Elif

Python One Line Function

Python One Line For Loop

Python One Line For Loop If

Python One Line For Loop Lambda

Python One Line While Loop

Python One Line HTTP Web Server

Want to create your own webserver in a single line of Python code? No problem, just use this command in your shell:

$ python -m http.server 8000

The terminal will tell you:

Serving HTTP on 0.0.0.0 port 8000

To shut down your webserver, kill the Python program with CTRL+c.

This works if you’ve Python 3 installed on your system. To check your version, use the command python --version in your shell.

You can run this command in your Windows Powershell, Win Command Line, MacOS Terminal, or Linux Bash Script.

You can see in the screenshot that the server runs on your local host listening on port 8000 (the standard HTTP port to serve web requests).

Note: The IP address is NOT 0.0.0.0—this is an often-confused mistake by many readers. Instead, your webserver listens at your “local” IP address 127.0.0.1 on port 8000. Thus, only web requests issued on your computer will arrive at this port. The webserver is NOT visible to the outside world.

Python 2: To run the same simple webserver on Python 2, you need to use another command using SimpleHTTPServer instead of http:

$ python -m SimpleHTTPServer 8000
Serving HTTP on 0.0.0.0 port 8000 ...

If you want to start your webserver from within your Python script, no problem:

import http.server
import socketserver PORT = 8000 Handler = http.server.SimpleHTTPRequestHandler with socketserver.TCPServer(("", PORT), Handler) as httpd: print("serving at port", PORT) httpd.serve_forever()

You can execute this in our online Python browser (yes, you’re creating a local webserver in the browser—how cool is that)!

This code comes from the official Python documentation—feel free to read more if you’re interested in setting up the server (most of the code is relatively self-explanatory).

Source: Python One-Liner Webserver HTTP

Python One Line Webshell

Python One Line Write String to File

Python One Line Quine

Python One Line Quicksort

In this one-liner tutorial, you’ll learn about the popular sorting algorithm Quicksort. Surprisingly, a single line of Python code is all you need to write the Quicksort algorithm!

Problem: Given a list of numerical values (integer or float). Sort the list in a single line of Python code using the popular Quicksort algorithm!

Example: You have list [4, 2, 1, 42, 3]. You want to sort the list in ascending order to obtain the new list [1, 2, 3, 4, 42].

Short answer: The following one-liner solution sorts the list recursively using the Quicksort algorithm:

q = lambda l: q([x for x in l[1:] if x <= l[0]]) + [l[0]] + q([x for x in l if x > l[0]]) if l else []

You can try it yourself using the following interactive code shell:

Now, let’s dive into some details!

The following introduction is based on my new book “Python One-Liners” (Amazon Link) that teaches you the power of the single line of code (use it wisely)!

Python One-Liners

Introduction: Quicksort is not only a popular question in many code interviews – asked by Google, Facebook, and Amazon – but also a practical sorting algorithm that is fast, concise, and readable. Because of its beauty, you won’t find many introduction to algorithm classes which don’t discuss the Quicksort algorithm.

Overview: Quicksort sorts a list by recursively dividing the big problem (sorting the list) into smaller problems (sorting two smaller lists) and combining the solutions from the smaller problems in a way that it solves the big problem. In order to solve each smaller problem, the same strategy is used recursively: the smaller problems are divided into even smaller subproblems, solved separately, and combined. Because of this strategy, Quicksort belongs to the class of “Divide and Conquer” algorithms.

Algorithm: The main idea of Quicksort is to select a pivot element and then placing all elements that are larger or equal than the pivot element to the right and all elements that are smaller than the pivot element to the left. Now, you have divided the big problem of sorting the list into two smaller subproblems: sorting the right and the left partition of the list. What you do now is to repeat this procedure recursively until you obtain a list with zero elements. This list is already sorted, so the recursion terminates.

The following Figure shows the Quicksort algorithm in action:

Figure: The Quicksort algorithm selects a pivot element, splits up the list into (i) an unsorted sublist with all elements that are smaller or equal than the pivot, and (ii) an unsorted sublist with all elements that are larger than the pivot. Next, the Quicksort algorithm is called recursively on the two unsorted sublists to sort them. As soon as the sublists contain maximally one element, they are sorted by definition – the recursion ends. At every recursion level, the three sublists (left, pivot, right) are concatenated before the resulting list is handed to the higher recursion level.

You create a function q which implements the Quicksort algorithm in a single line of Python code – and thus sorts any argument given as a list of integers.

## The Data
unsorted = [33, 2, 3, 45, 6, 54, 33] ## The One-Liner
q = lambda l: q([x for x in l[1:] if x <= l[0]]) + [l[0]] + q([x for x in l if x > l[0]]) if l else [] ## The Result
print(q(unsorted))

What is the output of this code?

## The Result
print(q(unsorted))
# [2, 3, 6, 33, 33, 45, 54]

Python One Line With Statement

Python One Line Exception Handling

Python One Line Try Except

Python One Line Execute

Python One Line Reverse Shell

Python One Line Read File

Python One Line Return If

Python One Line Regex Match

Python One Line Recursion

Python One Line Regex

Python One Line Read File to List

Python One Line Read Stdin

Python One Line Replace

Python One Line Ternary

Ternary (from Latin ternarius) is an adjective meaning “composed of three items”. (source) So, literally, the ternary operator in Python is composed of three operands.

Syntax: The three operands are written in an intuitive combination ... if ... else ....

<On True> if <Condition> else <On False>
Operand Description
<On True> The return expression of the operator in case the condition evaluates to True
<Condition> The condition that determines whether to return the <On True> or the <On False> branch.
<On False> The return expression of the operator in case the condition evaluates to False
Operands of the Ternary Operator

Let’s have a look at a minimum example in our interactive code shell:

Exercise: Run the code and input your age. What’s the output? Run the code again and try to change the output!

Python One Line Two For Loops

Python One Line True False

Python One Line Too Long

Python One Line Two Commands

Python One Line To Multiple Line

Python One Line URL Decode

Python One Line Or

Python One Line Object

Python One Line Open File

Python One Line Print

Python One Line Print For Loop

Python One Line Print If

Python One Line Print List

Python One Line Parse JSON

Python One Line Pretty Print JSON

Python One Line Array Filter

Python One Line Append

Python One Line And Or

Python One Line Conditional Assignment

Python One Swap

Python One Line Sum

Python One Line Sort

Python One Line Semicolon

Python One Line Dictionary

Python One Line Function Definition

Python One Line Def

Python One Line Docstring

Python One Line Dict Comprehension

Python One Line Double For Loop

Python One Line Download File

Python One Line For Loop Append

Python One Line Generator

Python One Line FizzBuzz

Python One Line HTTP Get

Python Global in One Line

Python One Line Hello World

Python One Line Comment

Python One Line Class

Python Define Two Variables in One Line

Python Define Multiple Variables in One Line

Python One Line If (Not) None

Python One Line Map

Posted on Leave a comment

How to Create a List of Dictionaries in Python?

Problem: Say, you have a dictionary {0: 'Alice', 1: 'Bob'} and you want to create a list of dictionaries with copies of the original dictionary: [{0: 'Alice', 1: 'Bob'}, {0: 'Alice', 1: 'Bob'}, {0: 'Alice', 1: 'Bob'}].

d = {0: 'Alice', 1: 'Bob'} dicts = [{**d} for _ in range(3)]
print(dicts)
# [{0: 'Alice', 1: 'Bob'}, {0: 'Alice', 1: 'Bob'}, {0: 'Alice', 1: 'Bob'}]

You use list comprehension with a “throw-away” loop variable underscore _ to create a list of 3 elements. You can change the value 3 if you need more or fewer elements in your list.

The expression {**d} unpacks all (key, value) pairs from the original dictionary d into a new dictionary. For more information about the unpacking operator, see this Finxter blog tutorial.

The resulting list contains copies of the original dictionary. If you change one, the others won’t see that change:

dicts[0][2] = 'Frank'
print(dicts)
# [{0: 'Alice', 1: 'Bob', 2: 'Frank'}, {0: 'Alice', 1: 'Bob'}, {0: 'Alice', 1: 'Bob'}]

Only the first dictionary in the list contains the new key value pair (2: 'Frank') which proves that the dictionaries don’t point to the same object in memory. This would be the case if you’d use the following method of copying a list with a single dictionary:

d2 = {0: 'Alice', 1: 'Bob'} dicts2 = [d2] * 3
print(dicts2)
# [{0: 'Alice', 1: 'Bob'}, {0: 'Alice', 1: 'Bob'}, {0: 'Alice', 1: 'Bob'}]

The method looks right but all three dictionaries are essentially the same:

dicts2[0][2] = 'Frank'
print(dicts2)
# [{0: 'Alice', 1: 'Bob', 2: 'Frank'}, {0: 'Alice', 1: 'Bob', 2: 'Frank'}, {0: 'Alice', 1: 'Bob', 2: 'Frank'}]

If you change one, you change all.

You can see this effect yourself in the following memory visualizer tool:

Exercise: change the method to the correct one so that the change affects only the first dictionary!

Related articles: How to create a Python list?

Where to Go From Here?

Enough theory, let’s get some practice!

To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

Practice projects is how you sharpen your saw in coding!

Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?

Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!

Posted on Leave a comment

Zip With List Output Instead of Tuple | Most Pythonic Way

Short answer: Per default, the zip() function returns a zip object of tuples. To obtain a list of lists as an output, use the list comprehension statement [list(x) for x in zip(l1, l2)] that converts each tuple to a list and stores the converted lists in a new nested list object.

Intermediate Python coders know the zip() function. But if you’re like me, you’ve often cursed the output of the zip function: first of all, it’s a zip object (and not a list), and, second, the individual zipped elements are tuples. But what if you need a list of lists as output? This article will show you the most Pythonic way of doing this.

Problem: Given a number of lists l1, l2, .... How ot zip the i-th elements of those lists together and obtain a list of lists?

Example: Given two lists [1, 2, 3, 4] and ['Alice', 'Bob', 'Ann', 'Liz'] and you want the list of lists [[1, 'Alice'], [2, 'Bob'], [3, 'Ann'], [4, 'Liz']].

l1 = [1, 2, 3, 4]
l2 = ['Alice', 'Bob', 'Ann', 'Liz']
# ... calculate result ...
# Output: [[1, 'Alice'], [2, 'Bob'], [3, 'Ann'], [4, 'Liz']]

Here’s a quick overview of our solutions:

Exercise: Create a new list l3 and change the four methods to zip together all three lists (instead of only two).

Method 1: Generator Expression

The first method uses a generator expression and converts the resulting iterable to a list using the list() constructor.

l1 = [1, 2, 3, 4]
l2 = ['Alice', 'Bob', 'Ann', 'Liz'] # Method 1
zipped = list(list(x) for x in zip(l1, l2)) print(zipped)
# [[1, 'Alice'], [2, 'Bob'], [3, 'Ann'], [4, 'Liz']]

This is efficient but not the most concise way of accomplishing this task.

Method 2: List Comprehension

A better way is to use list comprehension which is like a generator expression but it creates a list directly without the need to convert an iterable to a list (as in Method 1).

l1 = [1, 2, 3, 4]
l2 = ['Alice', 'Bob', 'Ann', 'Liz'] # Method 2:
zipped = [list(x) for x in zip(l1, l2)] print(zipped)
# [[1, 'Alice'], [2, 'Bob'], [3, 'Ann'], [4, 'Liz']]

Method 3: For Loop and Zip

Coders who don’t like list comprehension and generator expressions (or, who don’t understand these beautiful Python features) often use a simple for loop. In the loop body, you convert each tuple in the zip object to a list and append this list to the nested list zipped.

l1 = [1, 2, 3, 4]
l2 = ['Alice', 'Bob', 'Ann', 'Liz'] # Method 3:
zipped = []
for t in zip(l1, l2): zipped.append(list(t)) print(zipped)
# [[1, 'Alice'], [2, 'Bob'], [3, 'Ann'], [4, 'Liz']]

This method is readable but less concise.

Method 4: For Loop and Indexing

This method is often used by coders who know neither the zip() method, nor list comprehension, nor generator expressions: loop over all indices and append a new list obtained by grouping the i-th elements to the list.

l1 = [1, 2, 3, 4]
l2 = ['Alice', 'Bob', 'Ann', 'Liz'] # Method 4:
zipped = []
for i in range(len(l1)): zipped.append([l1[i], l2[i]]) print(zipped)
# [[1, 'Alice'], [2, 'Bob'], [3, 'Ann'], [4, 'Liz']]

However, this method is least Pythonic, lengthy, and it works only for equally-sized lists.

Exercise: What happens if the first list has more elements than the second list?

Method 5: Zip() + Map() + List()

A functional way of solving this problem is the map() function that applies a function to each element of an iterable and returns a map object. You can pass the list() constructor to the map() function to convert each tuple in the zip object to a list. You can then convert the map object to a list.

l1 = [1, 2, 3, 4]
l2 = ['Alice', 'Bob', 'Ann', 'Liz'] # Method 5
print(list(map(list,zip(l1, l2))))
# [[1, 'Alice'], [2, 'Bob'], [3, 'Ann'], [4, 'Liz']]

I don’t recommend this method because functional programming may be difficult to understand for many beginner coders. Guido van Rossum, the creator of Python, disliked functional programming as well.

Discussion

The most Pythonic way to create a list of lists by zipping together multiple lists is the list comprehension statement [list(x) for x in zip(l1, l2)]. List comprehension is fast, efficient, concise, and readable. You can also extend it to the general case by adding more lists to the zip function: [list(x) for x in zip(l1, l2, l3, ..., ln)]. The zip() function is also robust against lists of different lengths. In this case, the elements up to the maximal index of the shortest list are zipped.

Where to Go From Here?

Enough theory, let’s get some practice!

To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

Practice projects is how you sharpen your saw in coding!

Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?

Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!

Posted on Leave a comment

Create a List of Random Numbers — The Most Pythonic Way

Do you want to initialize a list with some random numbers? In this article, I’ll show you four different way of accomplishing this—along with a short discussion about “the most Pythonic way”.

Problem: Given an integer n. Create a list of n elements in a certain interval (example interval: [0, 20]).

# n = 5 --> [2, 3, 1, 4, 3]
# n = 3 --> [10, 12, 1]
# n = 10 --> [8, 2, 18, 10, 4, 19, 5, 9, 8, 1]

Solution: Here’s a quick overview on how you can create a list of random numbers:

  • Method 1: [random.random() for _ in range(10)] to create a list of random floats.
  • Method 2: [random.randint(0, 999) for _ in range(10)] to create a list of random ints.
  • Method 3: randlist = []; for _ in range(10): randlist.append(random.randint(0, 99)) to create a list of random ints.
  • Method 4: randlist = random.sample(range(20), 10) to create a list of random ints.

You can try those yourself in our interactive code shell:

Exercise: Change the interval of each method to [0, <your age>] and run the code.

Method 1: List Comprehension to Random Float List [0, 1]

List comprehension is a compact way of creating lists. The simple formula is [expression + context].

  • Expression: What to do with each list element?
  • Context: What elements to select? The context consists of an arbitrary number of for and if statements.
# Method 1: List Comprehension Random Float List [0, 1]
import random
randlist = [random.random() for _ in range(10)]

In my Python shell, the result is the following:

print(randlist)
# [0.06472744987876633, 0.011889634172418173, 0.70189711954834, 0.030063483145627568, 0.22255082691969674, 0.26704646386061337, 0.3242939534531408, 0.1781476583083168, 0.5367990394305883, 0.7621210982784024]

In the code, you first import the random module.

Then, you create a list of random floats by repeatedly calling random.random() that generates a random float number between 0 and 1 each time it is called.

You call it ten times as defined in the context part for _ in range(10). Note that the underscore serves as a “throw-away” variable as you don’t actually need it to create the list.

Also note that the list comprehension statement evaluates the expression multiple times—and not only once in the beginning. That’s why all the numbers in the list are different.

You can easily extend the creation of floats in a larger interval by multiplying the randomly created float with a constant: [random.random() * 999 for _ in range(10)] would create a list of random floats in the interval [0, 999].

If you struggle with understanding list comprehension, watch my explainer video:

Using list comprehension to generate a list of random numbers is readable, concise, and efficient. Were it not for the fourth method, I’d consider this to be the most Pythonic way to create a list of random floats.

Method 2: List Comprehension to Random Integer List [0, 999]

Just for the sake of completeness, here’s the list comprehension statement that creates a list of random integers in the interval [0, 999]:

# Method 2: List Comprehension Random Int List [0, 999]
import random
randlist = [random.randint(0, 999) for _ in range(10)]

In my Python shell, the result is the following:

print(randlist)
# [298, 218, 58, 260, 485, 192, 588, 615, 42, 499]

You use the random.randint(0, 999) function to create a random integer value between start value 0 and end value 999, so all created integers are in the interval [0, 999].

This is a very Pythonic and readable way to create a list of random integers. You can stop reading right away and use it in your own code.

Method 3: For Loop Random Int List [0, 99]

An alternative that’s often used by non-Python coders is to use a simple for loop that does the same thing as list comprehension (but demanding more space):

# Method 3: For Loop Random Int List [0, 99]
import random
randlist = []
for _ in range(10): randlist.append(random.randint(0, 99))

In my Python shell, the result is the following:

print(randlist)
# [19, 35, 0, 13, 36, 15, 13, 65, 41, 99]

Again, you use the throw-away underscore variable as the random number is not a function of a loop variable. Each two calls to the random.randint() function are independent.

I’d consider this the least Pythonic way to solve this problem.

Method 4: random.sample()

Finally, we arrive at the most Pythonic way to solve this problem: stand on the shoulders of giants and use existing built-in functionality. The random.sample() method takes a “universe” from which the random numbers are drawn and a list size n—and draws n random numbers from your universe.

# Method 4: random.sample()
import random
# Generate 10 random numbers between 0 and 20 (included)
randlist = random.sample(range(20), 10)

In my Python shell, the result is the following:

print(randlist)
# [1, 3, 0, 14, 7, 9, 13, 4, 12, 8]

You use the universe range(20) of the first 20 integer numbers 0, …, 19 and draw 10 random elements from the universe. Note that per default, no duplicates are allowed. If the universe is small than the list size n, an error is thrown:

ValueError: Sample larger than population or is negative

Discussion

In this tutorial, you’ve learned four methods to solve the problem of creating a list of random numbers. Objectively, the most Pythonic way to accomplish this is the fourth method: use the random.sample() function as it’s implemented to do exactly this.

But subjectively, I’d use the first or second method based on list comprehension to create a list of random floats or integers.

Why? Because I’m lazy and knowing the random.random() and random.randint() functions is already enough to solve the problem effectively. In practice, I don’t want to waste too much energy trying to remember code functions that do neither improve readability, nor efficiency of my code.

Where to Go From Here?

Enough theory, let’s get some practice!

To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

Practice projects is how you sharpen your saw in coding!

Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?

Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!

Posted on Leave a comment

How to Create a Python List of Size n?

To create a list of n placeholder elements, multiply the list of a single placeholder element with n. For example, use [None] * 5 to create a list [None, None, None, None, None] with five elements None. You can then overwrite some elements with index assignments. In the example, lst[2] = 42 would result in the changed list [None, None, 42, None, None].

Let’s play with an interactive code shell before you’ll dive into the detailed solution!

Exercise: Initialize the list with n=20 placeholder elements -1 and run the code.


Next, you’ll learn about the more formal problem and dive into the step-by-step solution.

Problem: Given an integer n. How to initialize a list with n placeholder elements?

# n=0 --> []
# n=1 --> [None]
# n=5 --> [None, None, None, None, None]

Solution: Use the list concatenation operation *.

n = 5
lst = [None] * n
print(lst)
# [None, None, None, None, None]

You can modify the element n as you like. In subsequent operations, you can overwrite all placeholder None list elements using simple index assignment operations:

lst[0] = 'Alice'
lst[1] = 0
lst[2] = 42
lst[3] = 12
lst[4] = 'hello'
print(lst)
# ['Alice', 0, 42, 12, 'hello']

However, there’s a small problem if you want to create a list with mutable objects (such as a list of lists):

lst = [[]] * n
print(lst)
# [[], [], [], [], []] lst[2].append(42) print(lst)
# [[42], [42], [42], [42], [42]]

Changing one list element changes all list elements because all list elements refer to the same list object in memory:

The solution is to use list comprehension (see my detailed blog tutorial on list comprehension for a complete guide):

lst = [[] for _ in range(n)]
print(lst)
# [[], [], [], [], []] lst[2].append(42)
print(lst)
# [[], [], [42], [], []]

In the following visualization, you can see how each element now refers to an independent list object in memory:

Exercise: Run the visualization and convince yourself that only one element is modified! Why is this the case?

Where to Go From Here?

Enough theory, let’s get some practice!

To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

Practice projects is how you sharpen your saw in coding!

Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?

Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!

Posted on Leave a comment

Python SymPy — A Short Primer

What’s SymPy Anyway?

SymPy is a Python library for symbolic computation. So instead of approximating the result of the square root of 2, it keeps the square root intact—using a symbolic representation. This helps in further processing and can lead to situations where Python has introduced a floating point precision error without need. Here’s a basic example:

import sympy print(sqrt(3))
# sqrt(3)

The result is NOT an approximated square root of 3 like in the math package:

import math print(math.sqrt(3))
# 1.7320508075688772

An Interactive Example

You can try it yourself in the interactive code shell:

(Just click the image to create your own code!)

How to Install SymPy?

To install SymPy in Python, simply run the following command in your shell:

pip install sympy

This works for all major operating systems (MacOS, Windows, Linux). A preliminary is to have the pip package manager installed.

(Confused by all the libraries, modules, pip, and virtual environments? Read the ultimate library guide on my blog.)

To check whether it has installed correctly, simply run the following command in your Python shell:

>>> help(sympy)
Help on package sympy: NAME sympy DESCRIPTION SymPy is a Python library for symbolic mathematics. It aims to become a full-featured computer algebra system (CAS) while keeping the code as simple as possible in order to be comprehensible and easily extensible. SymPy is written entirely in Python. It depends on mpmath, and other external libraries may be optionally for things like plotting support. See the webpage for more information and documentation: https://sympy.org PACKAGE CONTENTS abc algebras (package) assumptions (package)

The output validates that the sympy package has installed correctly.

Where to Go From Here?

Enough theory, let’s get some practice!

To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

Practice projects is how you sharpen your saw in coding!

Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?

Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!

Posted on Leave a comment

How to Sort a List of Tuples? – Most Pythonic Way!

Did you already try to sort a list of tuples? And when you saw the result,
it wasn’t quiet what you expected? Well, this happend to me when I went deeper
into Python and I suppose, it also happend to you, since you are looking for
a solution. This defenitely shows that you are an advanced Python programmer already!

Quick Answer

Use Python’s built-in sorted() function or call the method sort() on the list
you want to sort. Both of them have an optional parameter key which accepts a
function. Pass a function here which computes a key-value from each tuple in the list to sort
the tuples by their computed key-values.
Example for sorting a list of tuples by their second entry:

lst = [(1, 2), (2, 3), (0, 3)]
lst.sort(key=lambda x: x[1])

How to Sort a List of Tuples by Any Element or Custom Value?

Let’s first frame our problem in more detail: We have a list of tuples which we want to sort by
their second element or sum of elements or anything else which is not the first element of the list.
The default behavior of both, sort() and sorted(), is taking the first entry of each tuple to
sort the list of tuples. This is what may lead to surprises for beginners.

Suppose, we want to sort a list of items like this one:

items = [ ("apple", 1.5), ("pear", 2.3), ("egg", 0.5), ("cherry", 0.2),
]

We could either sort the tuples by their first element which is the name, or by their second element, the item’s price. To achieve this, we could write a custom sort function. But this wouldn’t be very pythonic.
Instead we want to use the built-in functions which Python provides. Therefore we have to options:

  1. call sort() on the list (items.sort())
  2. use sorted() to sort the list (sorted_items = sorted(items))

The difference between the two options is that the first one sorts the list in place and the second one creates a new list instance and adds the sorted items to this new instance. So in both cases you end up with a sorted list. If you need to preserve the list’s initial state use sorted(), in any other case you should prefer calling sort() directly on the list. In both cases the list will be sorted by Python’s default: Each tuple’s first entry.
To override the default behavior we use the optional parameter key which is provided by both sort() and sorted(). The parameter key expects a function which can compute a value from a tuple. It is very common to use a lambda to override the default behavior. If you are not yet familiar with Python’s lambdas read all the background knowledge in this article.

To sort the list items by the tuples’ second entry we write:

items.sort(key=lambda x: x[1])

or if you want to preserve the initial order of the items:

new_list = sorted(items, key=lambda x: x[1])

Our key function takes a tuple x and returns it’s second entry, thus, the final ordering of the list
will only take into account each tuple’s second entry.
We could also write:

items.sort(key=lambda x: sum(x))

to sort the tuples by the sum of their entries. Of course, this is not applicable for our example, since the entries of our tuples are strings and integers.

Finally, it is also important to be aware of Python’s default behavior for sorting lists of tuples.
It doesn’t make sense to write:

items.sort(key=lambda x: x[0])

because this is just what the default behavior does.

To sum it all up, watch this video:

Conclusion

Python provides everything you need to sort lists of tuples easily without writing custom sorting functions. All you need to do is define the key-function which computes a value for each tuple by which they should be sorted.

Posted on Leave a comment

Python Tuple to Integer

You have a tuple of integers—but you want a single integer. What can you do?

Problem: Given a tuple of values.

t = (1, 2, 3)

Your goal is to convert it to a single integer value.

There are multiple ways of accomplishing this (dependent on what exactly you want to do). Let’s get a quick overview in our interactive Python shell:

Exercise: Modify method 2 to calculate the average and round to the next integer!

Let’s dive into each of the method.

Method 1: sum()

The first way of converting a tuple to an integer, simply sum up all values. The sum() function is built-in in Python and you can use it on any iterable:

The syntax is sum(iterable, start=0):

Argument Description
iterable Sum over all elements in the iterable. This can be a list, a tuple, a set, or any other data structure that allows you to iterate over the elements.
Example: sum([1, 2, 3]) returns 1+2+3=6.
start (Optional.) The default start value is 0. If you define another start value, the sum of all values in the iterable will be added to this start value.
Example: sum([1, 2, 3], 9) returns 9+1+2+3=15.

Here’s how you can use the sum() function to sum over all values in an iterable (such as a tuple):

# Method 1: sum()
t = (1, 2, 3)
i = sum(t)
print(i)
# 6

In this case, it calculates 1+2+3=6. You can learn more about the sum() function on this Finxter blog article.

But what if you want to use all tuple values as digits of a larger integer value?

Method 2: str() + list comprehension + join()

List comprehension is a compact way of creating lists. The simple formula is [expression + context].

  • Expression: What to do with each list element?
  • Context: What elements to select? The context consists of an arbitrary number of for and if statements.

You can use it in combination with the sum() function to calculate the integer 123 from the tuple (1, 2, 3)—by using the tuple values as digits of the larger integer.

# Method 2: str() + list comprehension + join()
t = (1, 2, 3)
i = ''.join(str(x) for x in t)
print(int(i))
# 123

Well, to be frank, we didn’t even use list comprehension here—the correct term for str(x) for x in t is “generator expression”. The difference to list comprehension is that it creates a generator instead of a list.

If you like functional programming, you may like the following method:

Method 3: str() + map() + join()

The map() function creates a new iterable from an iterable by applying a function to each element of the original iterable:

You can pass the str() function into the map() function to convert each tuple element to a string.

Then, you can join all strings together to a big string. After converting the big string to an integer, you’ve successfully merged all tuple integers to a big integer value.

# Method 3: str() + map() + join()
t = (1, 2, 3)
i = ''.join(map(str, t))
print(i)
# 123

There are many details to the string.join() method. You can read the detailed tutorial on the Finxter blog. Here’s the short version:

The string.join(iterable) method concatenates all the string elements in the iterable (such as a list, string, or tuple) and returns the result as a new string. The string on which you call it is the delimiter string—and it separates the individual elements. For example, '-'.join(['hello', 'world']) returns the joined string 'hello-world'.

Method 4: Multiple Assignments

If you simply want to get multiple integers by assigning the individual tuple values to integer variables, just use the multiple assignment feature:

# Method 4: multiple assignments
t = (1, 2, 3)
a, b, c = t
print(a)
print(b)
print(c) '''
1
2
3 '''

Variables a, b, and c have the values 1, 2, and 3, respectively.

Where to Go From Here?

Enough theory, let’s get some practice!

To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

Practice projects is how you sharpen your saw in coding!

Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?

Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!