Is it possible to use the elements of two different lists as function parameters in Python?

Viewed 165

I have a function which needs to take two parameters like so

list_of_ids = [1,2,3]
list_of_names = [bob, joe, frank]
def function(id, name):
    

The function arguments come from those two arrays. So when it's called each time it will be like:

def function(1, bob)
def function(2, joe)
def function(3, frank)

I've tried a couple of for loops like so:

for id in list_of_ids:
    for name in list_of_names:
        function(id, name)

However this is not giving me the desired result. Any help will be appreciated.

2 Answers

You can use zip to combine two lists together.

Here is an example.

list_of_ids = [1,2,3]
list_of_names = ['bob', 'joe', 'frank']

def function(id, name):
    return f'{id} {name}'

for id,name in zip(list_of_ids,list_of_names):
    print(function(id,name))


#1 bob
#2 joe
#3 frank

zip creates an 'zip' object that is iterable tubles of the two lists/tuples passed to it.

In case those lists have unequal elements, it's better to handle in a generator as shown below:

def generate_result(lst1,lst2):
    counter = 0
    while counter < len(lst1) or counter < len(lst2):
        if counter >= len(lst1) :
            yield ("NA",lst2[counter]) # Replace with actual function call
        elif counter >= len(lst2) :
            yield (lst1[counter],"NA") # Replace with actual function call
        else:
            yield (lst1[counter],lst2[counter]) # Replace with actual function call
        counter += 1

list1 = [1,2]
list2 = ["John","James","Cat","Dog","Bed","Red","Some","More"]

for i in generate_result(list1,list2):
    print(i)

Related