Python Forum
New to Python, How does this lambda expression works?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
New to Python, How does this lambda expression works?
#1
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!
Reply
#2
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
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#3
Oh! I can finally understand it. Thanks a lot!!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Convert any Python expression to a string voidtrance 2 1,129 Jun-23-2025, 07:06 AM
Last Post: DeaD_EyE
  Python beginner that needs an expression added to existing script markham 1 1,955 Sep-04-2023, 05:24 AM
Last Post: Pedroski55
  Add two resultant fields from python lambda function klllmmm 4 2,605 Jun-06-2023, 05:11 PM
Last Post: rajeshgk
  Python Regular expression, small sample works but not on file Acernz 5 5,377 Jun-09-2021, 08:27 PM
Last Post: bowlofred
  Using Regex Expression With Isin in Python eddywinch82 0 3,525 Apr-04-2021, 06:25 PM
Last Post: eddywinch82
  "Automate the Boring Stuff with Python" creating a path works but only for CMD promt Milos 2 4,511 Nov-28-2020, 01:08 PM
Last Post: Larz60+
  Works with Curl. Can't get it to work in Python bazcurtis 3 5,010 May-07-2020, 07:47 AM
Last Post: bazcurtis
  Pass results of expression to another expression cmdr_eggplant 2 3,793 Mar-26-2020, 06:59 AM
Last Post: ndc85430
  time.sleep works erratically, a bug in Python? stipcevic 2 7,377 Jan-21-2020, 09:38 PM
Last Post: Marbelous
  How inheritance works in Python ARV 1 2,884 Oct-03-2019, 03:06 PM
Last Post: Larz60+

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020