Python | Assign multiple variables with list values

Python Methods and Functions

Method # 1: Using List Comprehension
Using List Comprehension makes it easy to do this task in one line. We run a loop for specific indexes in RHS and assign them to the required variables.

# Python3 demo code
# assign variables from list item
# use comprehension list

  
# initializing list

test_list = [ 1 , 4 , 5 , 6 , 7 , 3 ]

  
# print original list

print ( "The original list is:" + str (test_list))

 
# usage list of comprehension
# assign variables from list item

var1, var2, var3 = [test_list [i] for i in ( 1 , 3 , 5 )]

 
# result print

print ( "The variables are : " +   str (var1) +  

"" + str (var2) +

"" + str (var3))

Exit:

 The original list is: [1, 4, 5, 6, 7, 3] The variables are: 4 6 3 

Method # 2: Using itemgetter()
The itemgetter function can also be used to accomplish this specific task. This function takes the values ​​of the index and the container it is working on and assigns to the variables.

# Python3 demo code
# assign variables from list item
# using itemgetter ()

from operator import itemgetter

 
# initializing list

test_list = [ 1 , 4 , 5 , 6 , 7 , 3 ]

 
# print original list

print ( "The original list is:" + str (test_list))

  
# using using itemgetter ()
# assign variables from the list item

var1, var2, var3 = itemgetter ( 1 , 3 , 5 ) (test_list)

 
# print result

print ( "The variables are:" +   str (var1) +

"" + str (var2) +

"" + str (var3))

Exit:

 The original list is: [1, 4, 5, 6, 7 , 3] The variables are: 4 6 3 

Method # 3: Using itertools.compress()
The compression function takes boolean values corresponding to each index y as True if it should be assigned to a variable, and False it should not be used in an assignment to a variable.

# Python3 demo code
# assign variables from list item
# using itertools.compress ()

from itertools import compress

 
# initializing list

test_list = [ 1 , 4 , 5 , 6 , 7 , 3 ]

 
# print original list

print ( "The original list is: " + str (test_list))

 
# use with itertools.compress ()
# assign variables from list item

var1, var2, var3 = compress (test_list, ( 0 , 1 , 0 , 1 , 0 , 1 , 0 ))

 
# print result

print ( "The variables are:" +   str (var1) +  

"" + str (var2) +

  "" + str (var3))

Output:

 The original list is: [1, 4, 5, 6, 7, 3] The variables are: 4 6 3 




Get Solution for free from DataCamp guru