List as argument to user-defined functions

 

List as an argument to user-defined functions

When you pass a list to a function, the function gets a reference to the list. If the function modifies a list parameter, the caller sees the change. The following program demonstrates, how to pass a list as an argument to user-defined functions in python.

def disp(l1):
    for ele in l1:
        print (ele)

l1 = [10, 20, 30]
disp(l1)

Output

10
20
30

First, we create list l1. Then the list l1 is passed as an argument to function disp. The disp function prints the list to the output screen.

Another example, which accepts a list as an argument, deletes the head of the list (first element). The main function displays the rest of the elements. The parameter t and the variable letters are aliases for the same object.

#List arguments
def delete_head(t):
    del t[0]

letters = ['a', 'b', 'c']
print(letters)
delete_head(letters)
print(letters)

Output

[‘a’, ‘b’, ‘c’]

[‘b’, ‘c’]

An alternative is to write a function that creates and returns a new list. For example, tail returns all but the first element of a list:

#List arguments
def tail(t):
    return t[1:]

letters = ['a', 'b', 'c']

rest = tail(letters)
print(letters)
print(rest)

Output

[‘a’, ‘b’, ‘c’]

[‘b’, ‘c’]

Summary:

If you like the program please share it with your friends and share your opinion in the comment box. Like the Facebook page for regular updates and YouTube channel for video tutorials.

Leave a Comment

Your email address will not be published. Required fields are marked *