Here are ten useful Python tricks. Some of these are common mistakes when you are new to the language.
1. List derivation
You have a list: bag = [1, 2, 3, 4, 5]
1. List derivation
You have a list: bag = [1, 2, 3, 4, 5]
Now you want to double all the elements so that it looks like this: [2, 4, 6, 8, 10]
Most beginners, based on their previous language experience, will do something like this
bag = [1, 2, 3, 4, 5]
for i in range(len(bag)):
bag[i] = bag[i] * 2Copy the code
But there’s a better way:
bag = [elem * 2 for elem in bag]Copy the code
Pretty neat, right? This is called Python’s list derivation.
Check out Trey Hunner’s tutorial for more on list comprehensions.
2. Iterate over the list
Moving on, the list above.
Avoid this if possible:
bag = [1, 2, 3, 4, 5]
for i in range(len(bag)):
print(bag[i])Copy the code
Instead, it should look like this:
bag = [1, 2, 3, 4, 5]
for i in bag:
print(i)Copy the code
If X is a list, you can iterate over its elements. In most cases you don’t need an index for each element, but if you must, use the enumerate function. It looks like this:
bag = [1, 2, 3, 4, 5]
for index, element in enumerate(bag):
print(index, element)Copy the code
It’s pretty straightforward.
3. Swap elements
If you moved to Python from Java or C, you might be used to this:
A = 5 b = 10 # swap a and B TMP = a A = b b = TMPCopy the code
But Python provides a more natural and better way!
A = 5, b = 10 # Swap a and B a, b = b, ACopy the code
Pretty enough?
4. Initialize the list
If you were looking for a list of 10 integers 0, the first thing you might think is:
bag = []
for _ in range(10):
bag.append(0)Copy the code
Look, how elegant.
Note: this will produce a shallow copy if your list contains a list.
Here’s an example:
bag = [0] * 10Copy the code
Oops! All the lists have changed, and we just want to change the first list.
A change:
bag_of_bags = [[0] for _ in range(5)]
# [[0], [0], [0], [0], [0]]
bag_of_bags[0][0] = 1
# [[1], [0], [0], [0], [0]]Copy the code
Also remember:
“Premature optimization is the root of all evil”
Ask yourself, is it necessary to initialize a list?
5. Construct a string
You’ll often need to print strings. If there are many variables, avoid the following:
name = "Raymond"
age = 22
born_in = "Oakland, CA"
string = "Hello my name is " + name + "and I'm " + str(age) + " years old. I was born in " + born_in + "."
print(string)Copy the code
Well, how messy does this look? You can replace it with.format in a nice and concise way.
To do this:
name = "Raymond"
age = 22
born_in = "Oakland, CA"
string = "Hello my name is {0} and I'm {1} years old. I was born in {2}.".format(name, age, born_in)
print(string)Copy the code
Much better!
6. Return the tuples tuple
Python makes life easier by allowing you to return multiple elements in a function