Example of a simple for loop:
ints = [1, 2, 3, 4]
for i in ints:
plus_one.append(i + 1)
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)?
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.
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.