close

How to pass a list as an input of a function in Python

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to pass a list as an input of a function in Python in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How to pass a list as an input of a function in Python?

  1. How to pass a list as an input of a function in Python?

    You are currently returning a value from your function in the first iteration of your for loop. Because of this, the second and third iteration of your for loop never take place.

  2. pass a list as an input of a function in Python

    You are currently returning a value from your function in the first iteration of your for loop. Because of this, the second and third iteration of your for loop never take place.

Method 1

Why not side-step the problem altogether?

def square(vals):
    return [v*v for v in vals]

Edit: The first problem, as several people have pointed out, is that you are short-circuiting your for loop. Your return should come after the loop, not in it.

The next problem is your use of list.append – you need to call it, not assign to it, ie result.append(y*y)result.append = y*y instead overwrites the method with a numeric value, probably throwing an error the next time you try to call it.

Once you fix that, you will find another less obvious error occurs if you call your function repeatedly:

print(square([1,2,3])     # => [1, 4, 9]
print(square([1,2,3])     # => [1, 4, 9, 1, 4, 9]

Because you pass a mutable item (a list) as a default, all further use of that default item points back to the same original list.

Instead, try

def square(vals, result=None):
    if result is None:
        result = []
    result.extend(v*v for v in vals)
    return result

Method 2

You are currently returning a value from your function in the first iteration of your for loop. Because of this, the second and third iteration of your for loop never take place. You need to move your return statement outside of the loop as follows:

import math

def square(x):
    result = []
    for y in x:
        result.append(math.pow(y,2.0))
    return result 

print(square([1,2,3]))

Output

[1.0, 4.0, 9.0]

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read