Comprehension Syntax
Python has a really interesting syntax known as comprehension syntax. We might have a programming task that asks to append a value into an array based on a conditional. Specifically we will be doing list comprehension, but this same syntax can be used for sets, generators, and dictionaries. I would recommend reading the python documentation on these subjects, Docs: data structures.
In the code block below, the first example is the traditional control structure for computing a list. This takes up 4 different lines of code. The first is the declaration of the list, followed by the declaration of a for loop, a conditional, and finally the execution of the list's append function. A concrete example of this would be what if we wanted to create a list of odd numbers from 1 to n. Looking at the code our odd_list is declared as an empty list. A variable i is created as a value for our iterable, which in this case is the range function. I would recommend reading up on range if you'd like to know how it works, Docs: range. Now, the same block of code can be written to one line. The declaration of the list follows the same logic as before but the form is in a different order. This is an attractive solution to a problem as it only takes up one line of code.
Python
# result_list = []
# for value in iterable:
# if condition:
# result_list.append(expression)
odd_list = []
for i in range(1, 22):
if i % 2 != 0:
odd_list.append(i)
print(odd_list)
# result_list = [expression for value in iterable if condition]
new_odd_list = [j for j in range(1, 22) if j % 2 != 0]
print(new_odd_list)
Code copied
In conclusion, the major benefit of the Python language is its ablility to be incredibly compact, which could make code much easier to read as a result. I would recommend trying out more complex examples and different data structures to really grasp this concept.