Python function for Square in a provided list

青春壹個敷衍的年華 提交于 2021-02-08 12:11:23

问题


I have a list like [2,3,4,5] and i want square of these number using python function

Have tried below Python code

def square(list=[]):
    for i in list:
        new_value=[]
        new_value.append(i**2)
        return new_value

I get the square of only first entry in a list.

square(2,3,4)

回答1:


List comprehension makes this function a single liner and much clearer.

def square(x): 
    return [y**2 for y in x]



回答2:


Your method square is initialising new_value for every element in the list, and also your return is incorrectly placed inside the loop.

def square(list=[]):
    new_value=[]
    for i in list:
        new_value.append(i**2)
    return new_value


来源:https://stackoverflow.com/questions/58898374/python-function-for-square-in-a-provided-list

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!