In Python there’s a one-line syntax for iterating over elements of a list. I’ve always found it looked kind-of odd, and as I need to look it up all the time I decided to write a little TIL on this blog about it.
list = [1, 2, 3, 4] new_list = [num*2 for num in list] new_list == [2, 4, 6, 8] # |--- the function to call on each element # | |--- variable name for each item # | | |--- the list to work on # | | | [func(item) for item in list]
There are more powerful one-liners documented on the Python Wiki.
Leave a Reply