Python is one of my preferred languages. It’s by default highly readable and tends to favor code brevity. These and all the awesome additional libraries out there are the reason it is so popular among programmers of all origins. In this short article I will cover some Tips and Tricks for python lists I’ve encountered during development with python.

A python list is an ordered and mutable collection. It allows to have duplicate members, in contrast to sets. Tuples are more or less the same as lists, but they can not be altered. You can find all the functionality of a list here.

So here are 5 basic tips and tricks I’ve been picking up regarding lists.

Tip and Trick 1: List comprehension

List comprehension provides a concise way to create lists. Take the rather lengthy example using a for loop.

products = ['apple', 'banana', 'grapes', 'pear']
products_with_p = []
for product in products:
    if 'p' in product:
        products_with_p.append(product)
print(products_with_p)
# Output:
# ['apple', 'grapes', 'pear']

List comprehension allows us to transform this into a simple, yet readable, one liner. It is also possible to nest several list comprehensions, but be aware that it can get very unreadable quickly.

print([product for product in products if 'p' in product])
# Output:
# ['apple', 'grapes', 'pear']

Similar to list comprehensions: dictionary comprehensions also exist. Mind the slightly adapted syntax for the key-value pair that make up the list:

products_with_counts = {'apple': 5, 'banana': 7, 'grapes': 8, 'pear': 9}
products_count_above_7 = {k:v for (k,v) in products_with_counts.items() if v >= 7}
print(products_count_above_7)
# Output:
# {'banana': 7, 'grapes': 8, 'pear': 9}

Tip and Trick 2: Advanced list iterations

Iterating a list (or any iterable) is very easy in python using for … in … syntax.

for element in range(4):
    print(element)
# Output:
# 0
# 1
# 2
# 3

But what to do if you also need the index of the element? enumerate() helps by providing the current index for you.

products = ['apple', 'banana', 'grapes', 'pear']
for c, value in enumerate(products, 1):
    print(c, value)
# Output:
# 0 apple
# 1 banana
# 2 grapes
# 3 pear

What about iterating over multiple lists simultaneously? Here comes zip(). It will stop iterating when the shortest iterable is exhausted.

products = ['apple', 'banana', 'grapes', 'pear']
product_count = [5, 7, 8, 9, 10]
for count, product in zip(product_count, products):
    print(count, product)
# Output:
# 5 apple
# 7 banana
# 8 grapes
# 9 pear

Tip and Trick 3: Joining lists inside a dictionary

Sometimes you need to combine several nested lists inside a dictionary. Instead of doing it manually you can use the combination of dict.values() and the built-in sum function. Which leverages the fact that lists can be concatenated by the + operator e.g. [1, 2] + [3, 4] = [1, 2, 3, 4]

simple_dict = {"a": [1,2], "b":[3,4]}
values = sum(simple_dict .values(), [])
print(values)
# Output:
# [1, 2, 3, 4]

Tip and Trick 4: List to string

Often you need to be able to do the reverse of a tokenization, so that you join a list of objects back into a single item. This can be done quite easily in python using the built-in function join(). Here is an example:

tokens = ["Put", "me", "back", "together"]
print(" ".join(tokens))
# Output:
# "Put me back together"

Tip and Trick 5: Map and filter with lists

Map and filter are functions known from functional programming and allow us to apply functions to lists in a more concise way. Let’s dig into it.

product_prizes = [2, 1, 3, 1.5]
double_prices = list(map(lambda x: x**2, product_prizes))
print(double_prices)

prices_less_than_2 = list(filter(lambda x: x < 2, product_prizes))
print(prices_less_than_2)
# Output:
# [4, 1, 9, 2.25]
# [1, 1.5]

Conclusion

I hope those Tips and Tricks for python lists helps you to use lists much more effectively in the future!