List comprehensions

Example of a simple for loop:
ints = [1, 2, 3, 4]
plus_one =
for i in ints:
plus_one.append(i + 1)
print(plus_one)

List comprehensions equivalent:
plus_one = [i + 1 for i in ints]

My question: how does the list comprehensions equivalent knows that it needs to append the list. Is appending the list the only thing that a list comprehension can do (e.g. can it work with other methods that can manipulate lists)?

2 Likes

Hello @milanzkandic, we use List Comprehension to create lists in python. It’ll do so by executing the expression inside []. The expression generates elements in the list followed by a for loop over some collection of data which would evaluate the expression for every item in the collection.

Lean More…

https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions
https://towardsdatascience.com/all-about-python-list-comprehension-14dd979ec0d1


Yes @milanzkandic you can perform other operations like how you would do it in a usual for-loop. Bear in mind that your expected output is a list so there may be some operations/methods that will not work.

1 Like