Monday, 6 January 2025

Python Coding challenge - Day 322| What is the output of the following Python Code?

 


Code Explanation:

Input Data:

data = [(1, 'b'), (3, 'a'), (2, 'c')]

This line creates a list of tuples named data. Each tuple contains two elements:

A number (e.g., 1, 3, 2).

A string (e.g., 'b', 'a', 'c').

Sorting the Data:

sorted_data = sorted(data, key=lambda x: x[1])

sorted(iterable, key):

sorted is a Python built-in function that returns a sorted version of an iterable (like a list) without modifying the original.

The key argument specifies a function to determine the "sorting criteria."

key=lambda x: x[1]:

A lambda function is used to specify the sorting criteria.

The input x represents each tuple in the data list.

x[1] extracts the second element (the string) from each tuple.

The list is sorted based on these second elements ('b', 'a', 'c') in ascending alphabetical order.

Printing the Sorted Data:

print(sorted_data)

This prints the sorted version of the data list.

Output:

[(3, 'a'), (1, 'b'), (2, 'c')]

0 Comments:

Post a Comment

Popular Posts

Categories

100 Python Programs for Beginner (78) AI (35) Android (24) AngularJS (1) Assembly Language (2) aws (17) Azure (7) BI (10) book (4) Books (179) C (77) C# (12) C++ (82) Course (67) Coursera (231) Cybersecurity (24) data management (11) Data Science (129) Data Strucures (8) Deep Learning (21) Django (14) Downloads (3) edx (2) Engineering (14) Excel (13) Factorial (1) Finance (6) flask (3) flutter (1) FPL (17) Google (34) Hadoop (3) HTML Quiz (1) HTML&CSS (47) IBM (30) IoT (1) IS (25) Java (93) Leet Code (4) Machine Learning (61) Meta (22) MICHIGAN (5) microsoft (4) Nvidia (4) Pandas (4) PHP (20) Projects (29) Python (951) Python Coding Challenge (394) Python Quiz (47) Python Tips (3) Questions (2) R (70) React (6) Scripting (1) security (3) Selenium Webdriver (4) Software (17) SQL (42) UX Research (1) web application (8) Web development (4) web scraping (2)

Followers

Person climbing a staircase. Learn Data Science from Scratch: online program with 21 courses