Program to print square of elements of list #list #map #lambdaexpression #python #square

preview_player
Показать описание
Code:

Python
L1 = [5, 7, 22, 87, 97]
final_list = list(map(lambda x: x**2, L1))
print(final_list)
Use code with caution.
Explanation:

List Creation (L1):

The first line defines a list named L1.
This list contains five integer values: 5, 7, 22, 87, and 97.
map Function:

The line final_list = list(map(lambda x: x**2, L1)) uses the built-in map function in Python.
The map function applies a given function to all the items of an iterable (like a list) and returns an iterator containing the results.
In this case, the iterable is the list L1.
lambda Function (Anonymous Function):

Inside the map function, you have a lambda expression.
A lambda expression defines a small, anonymous function on the fly.
Here, the lambda function takes a single argument x.
The function body simply squares the argument (x**2). This means it calculates x multiplied by itself.
Applying the Function:

The map function iterates through the elements of L1.
For each element (x), it calls the lambda function, passing the current element as the argument (x).
The lambda function squares x and returns the result.
map builds an iterator that holds these squared values.
Creating final_list:

The list(map(...)) part converts the iterator returned by map into a concrete list named final_list.
This list now contains the squares of the elements in L1.
Printing the Result:

The print(final_list) line displays the contents of final_list to the console.
Output:

When you run this code, you'll see the following output:

[25, 49, 484, 7569, 9409]
This list contains the squares of the original numbers in L1.

In essence, this code squares each element in the list L1 and stores the results in a new list called final_list.
Рекомендации по теме
welcome to shbcf.ru