Top 5 Python Tricks for Beginners
- Benjamin

- Dec 15, 2018
- 1 min read
Updated: Dec 16, 2018

Python is full of beautiful simple tricks that make tricky things easier than most other languages. Here's our countdown:
FIVE
You can swap many numbers in place:
>>> a = 1
>>> b = 2
>>> c = 4
>>> d = 5
>>> print (a,b,c,d)
>>> d, c, b, a = a, b, c, d
>>> print (a,b,c,d)
Try it out!
FOUR
To reverse a list: L[::-1]. Couldn't be easier.
THREE
Use yagmail to send an email (don't annoy your friends with loops)!
>>> import yagmail
>>> mail = yagmail.SMTP({'email':'fakealias'},'password')
>>> mail.send('sender_add','subject','body')
TWO
Reflect an array or transpose a matrix:
>>> mat = [['a', 'b', 'c'], ['d', 'e', 'f']]
>>> zip(*mat)
>>> [('a', 'd'), ('b', 'e'), ('c', 'f')]
more on using * for unpacking later!
ONE
Merge two dictionaries!
>>> dict_1 = {'key1' : 1, 'key2' : 2}
>>> dict_2 = {'key3' : 3, 'key4' : 4}
>>> merged_dict = {**dict_1, **dict_2}
>>> merged_dict
>>> {'key4': 4, 'key1': 1, 'key3': 3, 'key2': 2}
Let us know your top moves!

Comments