Hi folks,
Can someone help me please? I am not sure I can get my head around the Lambda function. In the below example, what does the number ‘1’ stand for in item [1]? Thanks!
items = [
("mango", 2), ("pear", 50), ("tomato", 33), ("juice", 31), ("crisps", 23)
]
filtered = list(filter(lambda item: item[1] >= 1, items))
print(filtered)
Each item in the items list is a tuple, and you can get the values in a tuple by their index. So for example, this tuple…
("tomato", 33)
has two values, "tomato"
in position 0 and and 33
in position 1. So item[1]
for this tuple is 33
. So I think your lambda is saying, give me all the items in the list where the quantity (or whatever the second value represents) is 1 or greater.
Aahh, makes sense. Why did I not think of that? Thanks very much, that’s very helpful of you!