Python | Unpack whole list into variables
Sometimes, while working with list, we can have a wish to have each of element of list to be converted or unpacked into required variables. This problem can occur in web development domain. Let’s discuss certain ways in which this problem can be solved.
Method #1 : Using "=" operator
This task can be performed using a “=” operator. In this we just ensure enough variables as the count of list elements and assign them to list, the list elements get allotted to variables in order of their assignment.
# Python3 code to demonstrate working of# Unpack whole list into variables# using "=" operator # initialize listtest_list = [1, 3, 7, 4, 2] # printing original listprint("The original list is : " + str(test_list)) # Unpack whole list into variables# using "=" operatorone, two, three, four, five = test_list # printing resultprint("Variables as assigned are : " + str(one) + " " + str(two) + " " + str(three) + " " + str(four) + " " + str(five)) |
The original list is : [1, 3, 7, 4, 2] Variables as assigned are : 1 3 7 4 2
Method #2 : Using Namedtuple
This problem can be solved using a namedtuple, which can store the list elements with a variable name that can be accessed by using a dot operator succeeding with name of variable initialized.
# Python3 code to demonstrate working of# Unpack whole list into variables# using Namedtuplefrom collections import namedtuple # initialize listtest_list = [1, 3, 7, 4, 2] # printing original listprint("The original list is : " + str(test_list)) # Unpack whole list into variables# using Namedtupletemp = namedtuple("temp", "one two three four five")res = temp(*test_list) # printing resultprint("Variables as assigned are : " + str(res.one) + " " + str(res.two) + " " + str(res.three) + " " + str(res.four) + " " + str(res.five)) |
The original list is : [1, 3, 7, 4, 2] Variables as assigned are : 1 3 7 4 2


