No matter what exactly are you working on, if you are working with data, you also need a place where you can store this data.

There are many options and which one you choose depends on your wished outcome.

A very straightforward way of storing any kind of data are Arrays, or Lists, as they are named in Python.

Lists are one of 4 built-in data types in Python used to store collections of data, the other 3 are Tuple, Set, and Dictionary, all with different qualities and usage.

And as with other things, there are traditional ways of adding items into a List and then there is Pythonic way of doing the same thing.

Let’s see an example how would one append item into an Array normally:

1
2
3
4
numbers = []

for n in range(10):
   numbers.append(n)

Again this works and there is nothing wrong with it, however Python offers a simpler and cleaner solution known as List comprehension:

1
numbers = [n for n in range(10)]

Same result, but cleaner one-liner. A very elegant pythonic way of creating lists on the go.

You can use comprehension for different data types too:

1
2
3
4
5
dict_comp = {i: i * i for i in range(10)}
list_comp = [x*x for x in range(10)]
set_comp = {i%3 for i in range(10)}
# even for generators!
gen_comp = (2*x+5 for x in range(10))

How it helped me?

It’s a very useful feature that one would probably use on a daily basis, but the most recent application of List comprehension that comes to mind is from my Job scraper, where I even used more advanced List comprehension with a conditional statement:

1
2
# check for keywords in summary as well in title
match = [skill for skill in SKILLS if skill in job['summary'] or skill in job['title'].lower()]

Now using comprehensions always instead of actual loops is also not a good idea, as it always depends on the context and readability is also very important.

What I like about Python even more is that it has a very human-readable syntax. Even person who only barely tried to code would probably understand what’s going on here.