Assign multiple variables with a Python list values


Depending on the need of the program we may an requirement of assigning the values in a list to many variables at once. So that they can be further used for calculations in the rest of the part of the program. In this article we will explore various approaches to achieve this.

Using for in

The for loop can help us iterate through the elements of the given list while assigning them to the variables declared in a given sequence.We have to mention the index position of values which will get assigned to the variables.

Example

 Live Demo

listA = ['Mon', ' 2pm', 1.5, '11 miles']

# Given list
print("Given list A: " ,listA)

# using for in
vDay, vHrs, vDist = [listA[i] for i in (0, 2, 3)]

# Result
print ("The variables : " + vDay + ", " + str(vHrs) + ", " +vDist)

Output

Running the above code gives us the following result −

Given list A: ['Mon', ' 2pm', 1.5, '11 miles']
The variables : Mon, 1.5, 11 miles

With itemgetter

The itergetter function from the operator module will fetch the item for specified indexes. We directly assign them to the variables.

Example

 Live Demo

from operator import itemgetter

listA = ['Mon', ' 2pm', 1.5, '11 miles']

# Given list
print("Given list A: " ,listA)


# using itemgetter
vDay, vHrs, vDist = itemgetter(0, 2, 3)(listA)

# Result
print ("The variables : " + vDay + ", " + str(vHrs) + ", " +vDist)

Output

Running the above code gives us the following result −

Given list A: ['Mon', ' 2pm', 1.5, '11 miles']
The variables : Mon, 1.5, 11 miles

With itertools.compress

The compress function from itertools module will catch the elements by using the Boolean values for index positions. So for index position 0,2 and 3 we mention the value 1 in the compress function and then assign the fetched value to the variables.

Example

 Live Demo

from itertools import compress

listA = ['Mon', ' 2pm', 1.5, '11 miles']

# Given list
print("Given list A: " ,listA)

# using itemgetter
vDay, vHrs, vDist = compress(listA, (1, 0,1, 1))

# Result
print ("The variables : " + vDay + ", " + str(vHrs) + ", " +vDist)

Output

Running the above code gives us the following result −

Given list A: ['Mon', ' 2pm', 1.5, '11 miles']
The variables : Mon, 1.5, 11 miles

Updated on: 13-May-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements