Published: Oct. 18, 2019 by lukemakin |  estimated reading time: 11 minutes
python tips & tricks
In this article we will present 5 convenient ways to write better code in Python. We'll discuss each one of them with examples at the same time trying to provide as simplest explanation possible. Let's get started!

1. Generators If you don't want to display all items of the list at once you can use generators. To begin we shall explain 3 definitions related to this topic: Iteration is the process of taking one element at a time from given data structures which basicially hold the data together. Iterable is an object that can be used in iteration, i.e. with a for loop, while iterator is an object that keeps the state and holds the next() method.

Consider an example below:

numbers = [10, 20, 30, 40, 50]

def get_next_number():
for num in numbers:
return num


def get_next_number2():
for num in numbers:
yield num


gtr = get_next_number()
gtr2 = get_next_number2()

print(type(gtr))
print(type(gtr2))
print(hasattr(gtr, '__next__',))
print(hasattr(gtr2, '__next__',))

'''
Output:
<class 'int'>
<class 'generator'>
False
True
'''

Above we defined to functions and checked if assigned to a variable - what is it's type and does it contain the '__next__' method, so in first case we are dealing with a 'int' that doesn't consist of the __next__method, and in the second example we get a generator that has this method included. What is a generator? In simple words - it's a function defined in order to create a iterator.

Now let's tak a look how this works in practice:

x = get_next_number()
print(x)
print(x)
print(next(x))

'''
Output:
10
10
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-41-86787ebf2884> in <module>
2 print(x)
3 print(x)
----> 4 print(next(x))

TypeError: 'int' object is not an iterator
'''

So when using the 'traditional' function we don't have the state, so it's impossible to display one position at one time only. All we can do is to modify this function to display all the items in the list:


def get_all_numbers():
num_list = []
for num in numbers:
num_list.append(num)
return num_list

z = get_all_numbers()
print(z)

'''
Output:
[10, 20, 30, 40, 50]
'''

So let's take a look at the second case wit the get_next_number2 function:


y = get_next_number2()
print(y)

'''
Output:
<generator object get_next_number2 at 0x109251050>
'''

As an output we received a generator object, so let's try to use the state in order to display one item at the time only from the given list.


y = get_next_number2()
print(next(y))
print(next(y))
print(next(y))

'''
Output:
10
20
30
'''

As you can see, now we have the opportunity to display item one after another form the numbers list.

2. Enumerate 

This a simple and extremly useful function to keep count of iterations. Let's get straight to the point and look at the examples below to understand how it works. For starters, we could always avoid enumerate and use a traditional approach:

cities = ['New York', 'Warsaw', 'Berlin', 'Paris', 'Las Vegas']

i = 0
for city in cities:
i+=1
print(i, city)

'''
Output:
1 New York
2 Warsaw
3 Berlin
4 Paris
5 Las Vegas
'''

To make things simpler and in a shorter way let's now use enumerate:


for i, city in enumerate(cities, 1):
print(i, city)

'''
Output:
1 New York
2 Warsaw
3 Berlin
4 Paris
5 Las Vegas
'''

3. ZIP

The zip function is used in order to combine together two or more iterable dataset elements of the same lenght in to one. Let's have a look at the example:

country = ('Poland', 'Germany', 'USA', 'France', 'Japan')
capital = ('Warsaw', 'Berlin', 'Washington', 'Paris', 'Tokyo')

place = zip(country, capital)
place_dict = dict(zip(country, capital))

print(place)
print(place_dict)

'''
Output:
<zip object at 0x109325d20>
{'Poland': 'Warsaw', 'Germany': 'Berlin', 'USA': 'Washington', 'France': 'Paris', 'Japan': 'Tokyo'}
'''

By zipping together two tuples we received as an output a zip object. After converting it to a dictionary, we were able to actually display the items with countries as keys, and capital as values. We can also perform a for loop and get back as an output tuples containing single values of country and capital:


for place in list(zip(country, capital)):
print(place)

'''
Output:
('Poland', 'Warsaw')
('Germany', 'Berlin')
('USA', 'Washington')
('France', 'Paris')
('Japan', 'Tokyo')
'''

4. List comprehension

Use list comprehension to build lists in a simpler and shorter way. Let's go back for a second to se the get_all_numbers (from the section regarding generators) and write it in a different way:

numbers = [10, 20, 30, 40, 50]

def get_all_numbers():
num_list = [x for x in numbers]
return num_list

z = get_all_numbers()
print(z)

'''
Output:
[10, 20, 30, 40, 50]
'''

More advanced use of list comprehension is described over here: https://www.pyplane.com/blog/map-filter-conditional-list-comprehension/

5. Return multiple values from a function

In python we have a very useful and powerful funcionality to return multiple values out of an function. Consider the example below:

def get_coordinates():
x = random.randint(1,10)
y = random.randint(1,100)
return x,y

print(type(get_coordinates()))

corr = get_coordinates()
first, second = get_coordinates()

print('first coordinate ', first)
print('second coordinate ', second)

'''
<class 'tuple'>
first coordinate 2
second coordinate 74
'''

The function above returns a tuple that can be unpacked by assigning variables to this function seperated by a comas. If the quantity of variables doesn't match the values, we can use the " * " operator by a particular variable to unpack the remaining values to it. This variable will hold a list of values. Below we modified our example in order to present this concept:


def get_coordinates():
x = random.randint(1,10)
y = random.randint(1,100)
z = random.randint(1,200)
return x, y, z

corr = get_coordinates()
first, *second = get_coordinates()

print('first coordinate ', first)
print('second coordinate ', second)

'''
Output:
first coordinate 9
second coordinate [38, 27]
'''

This is it for this article. Please let me know in the comments if there is something that need clarification. Cheers!

 
Extras
To view additional content login or create a free account
Categories:
Share your thoughts

No comments yet...

Signup to the newsletter
To get the latest updates from pyplane
© copyright 2019 pyplane.com