-3
l = [1,2,3,4,5,6,7,8]

print("list : ", l) 
n = int(input('N: ')) 
l = list(map(lambda x: x+n, l)) 
print("new list : ", l)

l = list(map(lambda x: x+n, l)) how does this code works?

scriptmonster
  • 2,741
  • 21
  • 29
albert
  • 1
  • 2
  • Read the docs about "map", "lambda" and "list" if not done yet. Edit the question to describe then what you think the line does and what exactly you don't understand. – Michael Butscher Oct 02 '22 at 06:49
  • These kind of code which handles lots of stuff is called as oneliners. In this case you need to understand `lambda` and `map`. Please also look for the term generators in python. – scriptmonster Oct 02 '22 at 06:52

2 Answers2

1

lambda use to create function (like def, but it's inline)

lambda x: x+n mean you insert x as parameter and it will return x+n

For example

f1 = lambda x: x+5
print(f1(10))

result is 15

You can see more here link

map use to apply function to every element in that list or list like such as tuple, array

see more here link

so in your case, if you input n=1, result is l=[2,3,4,5,6,7,8,9]

SoulCRYSIS
  • 559
  • 3
  • 14
0

This code add n to each element of the list. Read more about map and lambda function on https://docs.python.org/3/library/functions.html#map and https://python-reference.readthedocs.io/en/latest/docs/operators/lambda.html