Python Forum
New to Python, How does this lambda expression works? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: New to Python, How does this lambda expression works? (/thread-25312.html)



New to Python, How does this lambda expression works? - Joshh_33 - Mar-26-2020

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!


RE: New to Python, How does this lambda expression works? - buran - Mar-26-2020

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


RE: New to Python, How does this lambda expression works? - Joshh_33 - Mar-26-2020

Oh! I can finally understand it. Thanks a lot!!