Python is a very powerful programming language that understands structural, functional and object oriented programming paradigms. New comers to Python from other languages tend to carry with them their mother (programming) tongue culture. Although they achieve the required task, they might have fallen in the trap of using Python the wrong way. In this post, we cover some efficient tricks to achieve tasks in Python; we call it the Pythonic way. Find an IPython Notebook for all tricks here on our GitHub repository.
Lists, Tuples, Dictionaries and Sets
- Lists in Python can be heterogeneous; that’s they may include items from different data types.
heterogeneous_list = ["string", 0.1, True]
- Sum and length of a list:
integer_list = [1, 2, 3] list_sum = sum(integer_list) # equals 6 list_length = len(integer_list) # equals 3
- You can quickly create a list from a range of numbers:
x = range(10) # is the list [0, 1, ..., 9] x = range(3,15) # is the list [3, 4, ..., 14]
- Use negative indices to address elements from the end:
last_element = x[-1] # equals 14 next_to_last_element = x[-2] # equals 13
- Slice lists:
first_three = x[:3] # equals [3, 4, 5] three_to_end = x[3:] # equals [6, 7, ..., 14] one_to_four = x[1:5] # equals [4, 5, 6, 7] last_three = x[-3:] # equals [12 ,13 ,14] without_first_and_last = x[1:-1] # equals [4, 5, ..., 13] copy_of_x = x[:] # equals [3, 4, ..., 14]
- Check if an element is a member of a list:
1 in [1, 2, 3] # returns True 0 in [1, 2, 3] # returns False
- Concatenate lists:
x = [1, 2, 3] x.extend([4, 5, 6]) # x is now [1, 2, 3, 4, 5, 6]
x = [1, 2, 3] y = x + [4, 5, 6] # y is [1, 2, 3, 4, 5, 6] but x is unchanged
x = [1, 2, 3] x.append(9) # x is now [1, 2, 3, 9]
- Unpack lists:
x, y = [4, 5] # x is now 4 and y is now 5 _, y = [1, 2] # y is now 2, don't care about the first element
- Reverse a list:
x = [1, 2, 3, 4] y = x[::-1] # y is now [4, 3, 2, 1]
- Sort a list:
x = [6, 1, -8, 15] y = sorted(x) # y is [-8, 1, 6, 15], x is unchanged x.sort() # x is sorted
- List comprehensions:
even_numbers = [x for x in range(5) if x % 2 == 0] # [0, 2, 4] squares = [x*x for x in range(5)] # [0, 1, 4, 9, 16] even_squares = [x*x for x in even_numbers] # [0, 4, 16] zeroes = [0 for _ in range(5)] # [0, 0, 0, 0, 0] # another way to generate zeros from the numpy package import numpy as np np.zeros(5) # [0, 0, 0, 0, 0]
- Tuples are similar to lists and are indicated using ()
my_tuple = (1, 2, 3)
The difference is that tuples are immutable (cannot add/remove items). Tuples are faster than lists if you are going to define a constant set of values to iterate through.
- Dictionaries are a set of key-value pairs. Keys can be strings, integers or tuples. Values have no restriction. A key cannot point to more than one value (but the value can be a list)
my_dict = {'Name': 'Zara', 'Class': 'First', 'Age': 7, 'Fruits': ['Apple', 'Banana']}
- Sets are unordered collection with no duplicate elements.
my_set = set(['a', 'b']) x = list(set([1, 2, 1, 3, 5, 2, 3, 1])) # x is now [1, 2, 3, 5]
- From lists to dictionaries:
square_dict = {x: x*x for x in range(5)} # {0:0, 1:1, 2:4, 3:9, 4:16}
- From lists to sets:
square_set = {x*x for x in [1, -1]} # set([1])
Functions
- Power operator:
5**2 # 25
- Floating point divisions all the time:
# For Python < 3 (check your python version) from __future__ import division # ensures that / operator performs floating point divisions
- Return more than one value:
def sum_and_average(my_list): s = sum(my_list) a = s / len(my_list) return s, a my_sum, my_average = sum_and_average([1, 2, 3]) # my_sum is now 6 and my_average is now 2
- The all() function takes a list and returns True precisely when every element is True. It tries to find a false element to negate the whole condition
all([True, 1, {3}]) # True all([True, 1, {}]) # False, {} is false all([]) # True, no false element in the list
- The any() function takes a list and returns True when at least one element is True. It tries to find any true element to prove the whole condition to be true
any([True, 1, {}]) # True any([]) # False, no true element in the list
- Apply a function to all elements of a list:
integer_list = [1, 2, 3] string_list = map(str, integer_list) # ["1", "2", "3"]
Looping & Enumeration
- Iterate through a list:
for element in [1, 2, 3]: print element
- Iterate through a list using both elements and their indices:
for i, element in enumerate([7, 13, 15]): do_something()
Zip and Argument Unpacking
Frequently, you will need to zip two or more lists together. The zip function transforms multiple lists into a single list of tuples of corresponding elements.
list1 = ['a', 'b', 'c'] list2 = [1, 2, 3] zip(list1, list2) # is [('a', 1), ('b', 2), ('c', 3)]
and Unpack them:
letters, numbers = zip(*pairs)
Our friend Pedro finds this trick amazing:
analysis = zip(usernames, function_labels, durations, absolute_distances) analysis = sorted(analysis) analysis = zip(*analysis)
We will be continuously adding tricks to the post. If you frequently use a shorthand notation for some frequent task, please comment below so we include it ..
Amazing post !
Certainly a good programming language that I can learn in order to build some prototypes in less time.
This is amazing!
If only I knew this existed when I needed it…