Wednesday, June 22, 2022

 List Comprehension


This is a more compact, memory efficient and faster way to create a new list than using a loop.


mylist = [expression for item in iterable if condition == True]


with the condition as optional and expression can be any grouping of operations and data inputs, with or without the presence of item in the expression. 


The iterable can also be call to range()


Examples


cars  = ["sedan", "sporty", "van", "two door", "truck"]

mycars = [g for g in cars]                         # makes a new list identical to cars

othercars = [g for g in cars if  "t" in g]     # returns list items that contain the letter t

thecars = [g for g in range(3)]                  # returns cars at index 0, 1, 2


bigcars = ["bigger_" + g for g in cars if "a" in g] 

# returns cars with an a in the name and prepends the bigger_ string to each match



No comments:

Post a Comment