# Python Tricks

Here are some cool Python tricks you may not know about.

I believe that it's easiest to learn by example, so I won't be explaining something unless the example itself isn't explanatory enough. Let me know if in future you'd prefer a more in-depth explanation.

If you'd like to see more tricks in Python, JavaScript, or any other language, please let me know!

And without further ado, let's begin!

## Swap the Value of Two Variables

```
a = 3
b = 4
print(f"A is currently {a} and B is currently {b}.")
# => A is currently 3 and B is currently 4.
# Now let's swap the variables.
a, b = b, a
print(f"A is currently {a} and B is currently {b}.")
# => A is currently 4 and B is currently 3.
```

You can also enclose the values in parentheses, which I find a little nicer.

```
a = 3
b = 4
(a, b) = (b, a)
print(f"A is currently {a} and B is currently {b}.")
# => A is currently 4 and B is currently 3.
```

Or in square brackets, if you prefer.

```
a = 3
b = 4
[a, b] = [b, a]
print(f"A is currently {a} and B is currently {b}.")
# => A is currently 4 and B is currently 3.
```

## Find the Smallest and Largest Values in a List

```
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
smallest = min(list)
largest = max(list)
print(f"The smallest value in the list is {smallest}, and the largest value in the list is {largest}.")
# => The smallest value in the list is 1, and the largest value in the list is 10.
```

## List Comprehensions

```
squares = [x**2 for x in range(20)]
# => [0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256, 289, 324, 361]
oddCubes = [x**3 for x in range(20) if x % 2 != 0]
# => [1, 27, 125, 343, 729, 1331, 2197, 3375, 4913, 6859]
```

This would be equivalent to the following code, which uses a more traditional imperative approach.

```
squares = []
for x in range(20):
squares.append(x**2)
oddCubes = []
for x in range(20):
if x % 2 != 0:
oddCubes.append(x**3)
```

## Remove Duplicates from a List

An easy way to remove duplicate values from a list is to convert the list to a set, and then back again. Sets are unordered data structures that don't allow duplicates.

```
dupe_list = [1, 2, 3, 1, 2, 3, 4, 5, 6, 4, 5, 6, 7, 7, 7]
clean_list = list(set(dupe_list))
print(clean_list)
# => [1, 2, 3, 4, 5, 6, 7]
```

It's worth noting for larger lists that this method isn't the most efficient.

## Reversing a List

The `reversed`

function produces a `list_reverseiterator object`

, which you can then convert into a list. Note that this doesn't modify the original list.

```
ord_list = [1, 2, 3, 4, 5]
rev_list = list(reversed(ord_list))
```

You can also reverse a list using a slice.

This syntax slices the entire list, but using a step of -1, which causes the list to be returned in reverse order.

Once again, this doesn't modify the original list, so you'll need to save it in a variable.

```
ord_list = [1, 2, 3, 4, 5]
rev_list = ord_list[::-1]
```

Using the `reverse`

method on a list will change it in place.

```
ord_list = [1, 2, 3, 4, 5]
ord_list.reverse()
print(ord_list)
# => [5, 4, 3, 2, 1]
```

## Use Lambdas for Small Functions

```
# Instead of having to type out an entire function definition, such as the below:
def sum(x, y):
return x + y
# We can use lambda functions to make this quicker and easier:
sum = lambda x, y: x + y
sum(3, 4)
# => 7
```

Python doesn't support multi-line lambdas, so this trick is only good for simple functions.

## Ternary Operator

Python supports the ternary operator using the below syntax.

```
a = 3
b = 4
max = a if a > b else b
min = a if a < b else b
print(f"The min is {min} and the max is {max}.")
# => The min is 3 and the max is 4.
```

## Combining Dictionaries

```
a = { 1: "a", 2: "b", 3: "c" }
b = { "d": 4, "e": 5, "f": 6 }
c = {**a, **b}
print(c)
# => { 1: 'a', 2: 'b', 3: 'c', 'd': 4, 'e': 5, 'f': 6 }
```

## Formatting Big Integers

Python allows you to use underscores within integer numbers to make reading them easier.

```
hundred_thousand = 100_000
million = 1_000_000
ten_million = 10_000_000
hundred_million = 100_000_000
billion = 1_000_000_000
```

## DivMod

I wanted to share this one as I doubt many people know about it.

divmod is a cool little function that returns a tuple containing both the quotient and remainder of a division.

```
divmod(7, 2)
# => (3, 1)
# Explanation: 2 goes into 7 a total of 3 times, with a remainder of 1.
# Without divmod, you'd have to perform 2 separate operations to get both numbers.
7 // 2 # Floor division to get the quotient.
7 % 2 # Modulus to get the remainder.
```

Once again, if you'd like to see more tricks in Python, JavaScript, or any other language, please let me know!

Thanks for reading!

### Did you find this article valuable?

Support **Joshua Rosato** by becoming a sponsor. Any amount is appreciated!