Python list comprehension - What does [x + 1 for x in a] mean?
Python list comprehension is to make a list from a list.
a = [1, 2, 3] b = [x + 1 for x in a] print(b) # [2, 3, 4]
b is a Python list and expressed by for statement. x iterates a and b is appended x+1.
To use a list comprehension is not necessary. This form is simple and beautiful for Python skilled programmars but if there are codes like this, the readability will be decreasing.
The following is still readable.
a = ['Apple', 'Microsoft'] b = [len(x) for x in a] print(b) # [5, 9]
But the next code may be less readable.
a = ['Apple', 'Microsoft'] b = [x.startswith('A') for x in a] print(b) # [True, False]
I am sure list comprehension should be used only when the function is arithmetic or one Python built-in function.
What is readable or unreadable depends on the programmar's experience and prefernce. I think Python code should be readable rather than simple. Over simplicity or beauty decreases the developement productivity.