Python Forum

Full Version: New to Python, How does this lambda expression works?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,

I would like to arrange the tuple in ascending order according to the price.
The first one,("Product1") is the name of the product,
while the second one, (10) is the price of the product.
It works perfectly when I type 1 there.

items = [
    ("Product1", 10),
    ("Product2", 9),
    ("Product3", 12),
]


items.sort(key=lambda item: item[1])
print(items)
The output would be like this.
Output:
[('Product2', 9), ('Product1', 10), ('Product3', 12)]
However, when I changed the item[1] to item[2], it shows error.

items = [
    ("Product1", 10),
    ("Product2", 9),
    ("Product3", 12),
]


items.sort(key=lambda item: item[2])
print(items)
Error:
Traceback (most recent call last): File "d:\.Coding Files\Python\HelloWorld\app.py", line 15, in <module> items.sort(key=lambda item: item[2]) File "d:\.Coding Files\Python\HelloWorld\app.py", line 15, in <lambda> items.sort(key=lambda item: item[2]) IndexError: tuple index out of range
Can someone explain how it works?
Some help would be much appreciated!
tuple indexes (as normal for python) start from 0. So, item[0] would be the first item in the tuple, and accordingly it will be sorted - e.g. if you had Product11 it will be before Product2
Oh! I can finally understand it. Thanks a lot!!