Member-only story
10 Useful Python Snippets To Code Like a Pro
Useful tips and tricks that I use every day
I’ve collected a list of useful tips and “tricks” I love to use when working with Python.
Feel free to bookmark this list and refer back to it later on, as it is tough to remember everything with just one look.
This list is in no particular order.
1. Swap Two Variables With One Line of Code
Can you think of a way to swap two variables without the help of a third temporary variable? Well, here it is:
a = 1
b = 2a, b = b, a
2. Duplicate Strings Without Looping
name = "Banana"
print(name * 4)
Output:
BananaBananaBananaBanana
3. Reverse a String
sentence = "This is just a test"
reversed = sentence[::-1]print(reversed)
Output:
tset a tsuj si sihT
4. Squash a List of Strings Into One String
You can easily join a list of strings using the built-in join()
method.
words = ["This", "is", "a", "Test"]
combined = " ".join(words)print(combined)
Output:
This is a Test
Feel free to check out more useful string methods in Python to save your day.
5. Comparison Chains
In Python, you can combine comparisons neatly together instead of splitting the statement into two or more parts. For example:
x = 100
res = 0 < x < 1000print(res)
Output:
True
6. Find the Most Frequent Element in a List
test = [6, 2, 2, 3, 4, 2, 2, 90, 2, 41]
most_frequent = max(set(test), key = test.count)print(most_frequent)
Output:
2