Python @ DjangoSpin

Python: Unpacking Iterables into Individual Variables

Buffer this pageShare on FacebookPrint this pageTweet about this on TwitterShare on Google+Share on LinkedInShare on StumbleUpon
Reading Time: 1 minutes

Unpacking Iterables into Individual Variables in Python

Unpacking Iterables into Individual Variables in Python

In Python, iterable objects can be decomposed into individual components in a single statement. This is called Unpacking. If you specify an incorrect number of variables while unpacking, Python will throw a ValueError.

########################
## UNPACKING A STRING ##
########################
>>> stringTen = "Hello"
>>> a,b,c,d,e = stringTen
>>> a
'H'
>>> b
'e'

####################
# UNPACKING A LIST #
####################
sentence = ["You", "can", "change", "me."]
word1, word2, word3, word4 = sentence
print( word1 )                         # 'You'
print( word3 )                         # 'change'

#####################
# UNPACKING A TUPLE #
#####################
coordinates = (20, 50, 100)
x, y, z = coordinates
print(x)                              # 20
print(y)                              # 50
print(z)                              # 100

##########################
# UNPACKING A DICTIONARY #
##########################
>>> IndianCricketTeam = dict(batsman = "V. Kohli", bowler = "B. Kumar")
>>> role1, role2 = IndianCricketTeam.keys()
>>> role1
'batsman'
>>> role2
'bowler'
 
>>> player1, player2 = IndianCricketTeam.values()
>>> player1
'V. Kohli'
>>> player2
'B. Kumar'

###################
# UNPACKING A SET #
###################
>>> setOfAnimals = {"cat", "dog", "elephant", "snake"}
>>> a, b, c, d = setOfAnimals
>>> a
'snake'
>>> b
'dog'
>>> c
'cat'
>>> d
'elephant

See also:

Buffer this pageShare on FacebookPrint this pageTweet about this on TwitterShare on Google+Share on LinkedInShare on StumbleUpon

Leave a Reply