Code Explanation:
Original List:
data = [(1, 3), (3, 1), (2, 2)]
This is a list of 3 tuples. Each tuple has two integers.
Sorting Logic:
sorted(data, key=lambda x: x[1])
The sorted() function returns a new sorted list without changing the original.
The key argument tells Python how to compare the elements.
lambda x: x[1] means: for each tuple x, use the second element (x[1]) as the sorting key.
Sorting in Action:
Let's evaluate the second elements:
(1, 3) → 3
(3, 1) → 1
(2, 2) → 2
Now, sort based on these values: 1, 2, 3
So the sorted order becomes:
[(3, 1), (2, 2), (1, 3)]
Output:
print(sorted_data)
This prints:
[(3, 1), (2, 2), (1, 3)]
.png)

0 Comments:
Post a Comment