With the advent of programming paradigms, there has been need to modify the way one codes. One such paradigm is OOPS. In this, we have a technique called modularity, which stands for making different modules/functions which perform independent tasks in program. In this, we need to pass more than just variable, but a list as well. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using tuple()
This task can be performed using the tuple()
. In this, we convert the pair list to tuple and by this way we separate individual elements as variables, ready to be sent to function.
# Python3 code to demonstrate working of # Split and Pass list as separate parameter # using tuple() # Helper function for demonstration def pass_args(arg1, arg2): print("The first argument is : " + str(arg1)) print("The second argument is : " + str(arg2)) # initialize list test_list = [4, 5] # printing original list print("The original list is : " + str(test_list)) # Split and Pass list as separate parameter # using tuple() one, two = tuple(test_list) pass_args(one, two)
Output :
The original list is : [4, 5] The first argument is : 4 The second argument is : 5
Method #2 : Using * operator
Using * operator is the most recommended method to perform this task. The * operator unpacks the dual list into args and hence solving our problem.
# Python3 code to demonstrate working of # Split and Pass list as separate parameter # using * operator # Helper function for demonstration def pass_args(arg1, arg2): print("The first argument is : " + str(arg1)) print("The second argument is : " + str(arg2)) # initialize list test_list = [4, 5] # printing original list print("The original list is : " + str(test_list)) # Split and Pass list as separate parameter # using * operator pass_args(*test_list)
Output :
The original list is : [4, 5] The first argument is : 4 The second argument is : 5
Australia
UK
UAE
Singapore
Canada
New
Zealand
Malaysia
USA
India
South
Africa
Ireland
Saudi
Arab
Qatar
Kuwait
Hongkong
Copyright 2016-2023 www.programmingshark.com - All Rights Reserved.
Disclaimer : Any type of help and guidance service given by us is just for reference purpose. We never ask any of our clients to submit our solution guide as it is, anywhere.