Suppose I have a function to calculate the square of a certain number. Now, I have a list of, for example, 100 numbers that I need to pass as the arguments. How do I pass each element of the list, one by one, as the argument to get the results?
CodePudding user response:
You can use a for loop:
def square(i):
return i ** 2
lst = [1,2,3,4,...]
for i in lst:
result = square(i)
print(result)
This works because the iterator, i
goes through every element in lst
and passes it as a parameter into our function, square()
.
I hope this helped! Let me know if you need any further clarification or details :)
CodePudding user response:
Use for
loop.
yourlist = [1,2,3,4...]
for i in yourlist:
yourfunction(i)
CodePudding user response:
def square(num):
return num ** 2
lt = [1..n]
for i in lt:
newElement = square(i)
print(newElement)
You can use this or you can append the new element in a new list and print the list of square of original list.
nlist = []
for i in list:
newEle = square(i)
nlist.append(newEle)
print(nlist)
You can do it by both ways.