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:
|
|
Again this works and there is nothing wrong with it, however Python offers a simpler and cleaner solution known as List comprehension:
|
|
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:
|
|
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:
|
|
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.