January 20, 2021 Stardate: 74518.8 Tagged as: Python
As a bonus, here are two of my favorite python one-liners:
Swapping Variables - no need to use temp variables. In some other languages, like C, you would need a temporary variable to hold a value while you swap them around. Something like this:
double a, b, temp; // Assign values to variables 5; a = 7; b = // Value of first variable is assigned to temp temp = a; // Value of second variable is assigned to the first a = b; // Value of temp (initial first) is assigned back to the second variable b = temp;
But in Python it’s a lot more… elegant.
# Assign values to variables = 5, 7 a, b # Swap values = b, aa, b
Multiple Variable Assignment - the above example shows another of my favorites. We can assign values to multiple variables with a single line. Even cooler is we can use an asterix and assign multiple values to a variable.
*b = [1, 2, 3, 4, 5] a, print(a, b)
> 1 [2, 3, 4, 5]
In the above code,
a is assigned the first element in the list while
b is assigned all the remaining.
*a, b = [1, 2, 3, 4, 5] print(a, b)
> [1, 2, 3, 4] 5
In the above code,
a is assigned all the elements except the last, and
b is assigned the last element in the list.
*b, c = [1, 2, 3, 4, 5] a, print(a, b, c)
> 1 [2, 3, 4] 5
Finally, in the above code,
a is assigned the first element,
c is assigned the last element, and
b is assigned all the elements in between.
List Comprehension - this is a really cool way to build a list without using loops. I’ve seen people go overboard on it where I couldn’t even understand what was going on. Here is the basic example:
# Silly loop example =  my_list for i in range(5): my_list.append(i) # List comprehension = [i for i in range(5)]my_list
Here is the syntax:
for item in iterable if condition == True][expression
so in the previous example,
= [i<expression> for i<item> in range(5)<iterable>]my_list
You can also get complex with the expression,
= [True, False, True] some_array = ["Hello" if i else "Goodbye" for i in some_array] my_list print(my_list)
> ['Hello', 'Goodbye', 'Hello']
In a previous post I did a multi-line if/elif/else replacement:
# Loop for i in range(1, 101): if (i%3==0 and i%5==0): print("FizzBuzz") elif i%3==0: print("Fizz") elif i%5==0: print("Buzz") else: print(i) # List Comprehension 'FizzBuzz' if (i%3==0 and i%5==0) else 'Fizz' if i%3==0 else 'Buzz' if i%5==0 else i for i in range(1, 101) ][
This is an automated list of software versions used during the writing of this article.
Software Version Python 3.7.4