Python – Construct variables of list elements

Sometimes, while working with python lists, we can have a problem in which we need to convert each element in list to variables and corresponding list as value. This can have application in many domains such as web development and day-day programming. Lets discuss certain ways in which this task can be performed.

Method #1 : Using dict() + zip()
The combination of above functions can be used to perform this task. In this, we zip both the list into a dictionary and key of dictionary can act as variable and value as variable value.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate 
# Construct variables of list elements
# using dict() + zip()
  
# Initializing lists 
test_list1 = ['gfg', 'is', 'best']
test_list2 = [1, 2, 3]
  
# printing original lists 
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
  
# Construct variables of list elements
# using dict() + zip()
res = dict(zip(test_list1, test_list2))
  
# printing result 
print ("Variable value 1 : " + str(res['gfg']))
print ("Variable value 2 : " + str(res['best']))

chevron_right


Output :



The original list 1 is : ['gfg', 'is', 'best']
The original list 2 is : [1, 2, 3]
Variable value 1 : 1
Variable value 2 : 3

 

Method #2 : Using global() + loop
This is yet another way to initialize variables as lists. In this we use global space to declare variables.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate 
# Construct variables of list elements
# using globals() + loop
  
# Initializing lists 
test_list1 = ['gfg', 'is', 'best']
test_list2 = [1, 2, 3]
  
# printing original lists 
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
  
# Construct variables of list elements
# using globals() + loop
for var, val in zip(test_list1, test_list2):
    globals()[var] = val
  
# printing result 
print ("Variable value 1 : " + str(gfg))
print ("Variable value 2 : " + str(best))

chevron_right


Output :

The original list 1 is : ['gfg', 'is', 'best']
The original list 2 is : [1, 2, 3]
Variable value 1 : 1
Variable value 2 : 3



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.