Python Programming Basics - Passing a List to a Function

When we talk about functions, we usually pass arguments (variables) into them. But what if you need to pass multiple values? You can use a list. Here’s how to do it. …

Updated November 19, 2023

When we talk about functions, we usually pass arguments (variables) into them. But what if you need to pass multiple values? You can use a list. Here’s how to do it.

# defining the function
def greetings(names):
    for name in names:
        print("Hello, " + name)

# calling the function with a list of names
greetings(['Alice', 'Bob', 'Charlie'])

In this code, we’re passing a list [‘Alice’, ‘Bob’, ‘Charlie’] to the greetings() function.

The function will then print out “Hello, Alice”, “Hello, Bob”, and “Hello, Charlie”. This is a simple demonstration of how you can pass multiple values to a function in Python using a list.

Remember that lists are very versatile in Python, they can hold different kinds of data types (integers, strings, etc.) which makes them perfect for passing to functions when working with complex problems or collections of data.

Stay up to date on the latest in Coding Python with AI and Data Science

Intuit Mailchimp