Translation: Wang Jian

Link: www.codeceo.com/article/pyt…

Original text: raymondtaught. Me/the python – -…

Here are ten useful Python tips and tricks. Some of these are common mistakes when you are new to the language.

Note: Assume we are all using Python 3

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

Try another way:

bag = [0] * 10
Copy the code

Look, how elegant.

Note: this will produce a shallow copy if your list contains a list.

Here’s an example:

bag_of_bags = [[0]] * 5 # [[0], [0], [0], [0]
bag_of_bags[0][0] = 1 # [[1], [1], [1], [1]
Copy 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]

bag_of_bags[0][0] = 1  
# [[1], [0], [0], [0]
Copy the code

Also remember:

“Premature optimization is the Root of all evil.” Ask yourself, is initializing a list necessary?

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 tuples

Python makes life easier by allowing you to return multiple elements in a function. But a common error occurs when unpacking tuples:

def binary():  
    return 0, 1

result = binary()  
zero = result[0]  
one = result[1]
Copy the code

It’s not necessary. You could have done this instead:

def binary():  
    return 0, 1

zero, one = binary()
Copy the code

If you want all elements to be returned, use an underscore _ :

zero, _ = binary()
Copy the code

That’s how efficient!

7. Access Dicts (Dictionary)

You’ll also often write key pair in dicts.

If you’re trying to access a nonexistent dict key, you might be tempted to do this to avoid KeyError:

countr = {}  
bag = [2, 3, 1, 2, 5, 6, 7, 9, 2, 7]  
for i in bag:  
    if i in countr:
        countr[i] += 1
    else:
        countr[i] = 1

for i in range(10):  
    if i in countr:
        print("Count of {}: {}".format(i, countr[i]))
    else:
        print("Count of {}: {}".format(i, 0))
Copy the code

However, using get() is a better way.

countr = {}  
bag = [2, 3, 1, 2, 5, 6, 7, 9, 2, 7]  
for i in bag:  
    countr[i] = countr.get(i, 0) + 1

for i in range(10):  
    print("Count of {}: {}".format(i, countr.get(i, 0)))
Copy the code

Of course you can use setdefault instead.

There’s an easier but more expensive way to do this:

bag = [2, 3, 1, 2, 5, 6, 7, 9, 2, 7]  
countr = dict([(num, bag.count(num)) for num in bag])

for i in range(10):  
    print("Count of {}: {}".format(i, countr.get(i, 0)))
Copy the code

You can also use the dict derivation.

countr = {num: bag.count(num) for num in bag}
Copy the code

These two methods are expensive because they traverse the list every time count is called.

8 using a library

Existing libraries just import and you can do what you really want.

Again, in the previous example, we built a function to count the number of times a number appears in a list. Well, there’s already a library that can do that.

from collections import Counter  
bag = [2, 3, 1, 2, 5, 6, 7, 9, 2, 7]  
countr = Counter(bag)

for i in range(10):  
    print("Count of {}: {}".format(i, countr[i]))
Copy the code

Some reasons to use libraries:

The code is correct and tested. Their algorithms will probably be optimal, so they’ll run faster. Abstractions: They are explicit and document-friendly, and you can focus on what hasn’t been implemented yet. In the end, it’s already there. You don’t have to reinvent the wheel.

9. Slice/step through the list

You can specify start points and stop points, like this list[start:stop:step]. Let’s take the first five elements of the list:

bag = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]  
for elem in bag[:5]:  
    print(elem)
Copy the code

So that’s slicing, and we specify that the stop point is 5, and before we stop, we’re going to get 5 elements out of the list.

What about the last five elements?

bag = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]  
for elem in bag[-5:]:  
    print(elem)
Copy the code

Don’t you get it? -5 means to take five elements from the end of the list.

If you want to interval elements in a list, you might do something like this:

bag = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]  
for index, elem in enumerate(bag):  
    if index % 2 == 0:
        print(elem)
Copy the code

But here’s what you should do:

bag = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]  
for elem in bag[::2]:  
    print(elem)
​
# or use rangesBag = list (range (0,10,2))print(bag)Copy the code

This is the step in the list. List [::2] means to iterate over the list and retrieve an element in two steps.

You can use list[::-1] for cool flipping lists.

10. TAB or space

In the long run, mixing tabs and Spaces can be a disaster, and you’ll see IndentationError: Unexpected indent. Whether you choose TAB or space, you should always use it in your files and projects.

One reason to use Spaces instead of tabs is that tabs are not the same in all editors. Depending on the editor used, tabs may be treated as 2 to 8 Spaces.

You can also use Spaces to define tabs when you write code. So you can choose how many Spaces to use as tabs. Most Python users use four Spaces.