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


Messages In This Thread
New to Python, How does this lambda expression works? - by Joshh_33 - Mar-26-2020, 01:58 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Python beginner that needs an expression added to existing script markham 1 722 Sep-04-2023, 05:24 AM
Last Post: Pedroski55
  Add two resultant fields from python lambda function klllmmm 4 945 Jun-06-2023, 05:11 PM
Last Post: rajeshgk
  Python Regular expression, small sample works but not on file Acernz 5 2,982 Jun-09-2021, 08:27 PM
Last Post: bowlofred
  Using Regex Expression With Isin in Python eddywinch82 0 2,307 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 2,902 Nov-28-2020, 01:08 PM
Last Post: Larz60+
  Works with Curl. Can't get it to work in Python bazcurtis 3 2,583 May-07-2020, 07:47 AM
Last Post: bazcurtis
  Pass results of expression to another expression cmdr_eggplant 2 2,309 Mar-26-2020, 06:59 AM
Last Post: ndc85430
  time.sleep works erratically, a bug in Python? stipcevic 2 3,921 Jan-21-2020, 09:38 PM
Last Post: Marbelous
  How inheritance works in Python ARV 1 1,853 Oct-03-2019, 03:06 PM
Last Post: Larz60+
  assignment: not an operator nor expression, but x=y=z=3 works fine? jefdaels 1 2,211 Jan-29-2019, 02:19 PM
Last Post: perfringo

Forum Jump:

User Panel Messages

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