How To Unpack List, Dictionary, Tuple In Python

satyabrata pal
ML and Automation
Published in
1 min readOct 1, 2019

Unpacking the technique which allows us to peel apart a python data structure and pass the contents of that data structure as function arguments. Here’s how to do it.

A Function To Play Around

Let’s say we have a function where we have a few arguments →

def unpackingExample(stark, lannister, hodor):
print(f'{stark} is a stark')
print(f'{lannister} is a lannister')
print(f'{hodor} is a hodor')

Let There Be Data

We have the following list, dictionary and tuple to unpack.

list = ['John Snow',  'Tywin', 'Hodor']
dict = {'stark': 'John Snow', 'lannister': 'Tywin', 'hodor': 'Hodor'}
tuple = ('John Snow', 'Tywin', 'Hodor')

Unpack Everything, Leave Nothing

Now, it’s time to start unpacking our stuff contained inside the data that we created in the previous section. Before the action begins the following points should be noted.

  1. Unpack list to function arguments using *
  2. Unpack dictionary to function arguments using **
  3. Unpack tuple to function arguments using *
  4. The order of elements in these data structures should be same as the arguments in the function.

Unpack the list as under →

unpackingExample(*list)Output
------
John Snow is a stark
Tywin is a lannister
Hodor is a hodor

Unpack the dictionary as under →

unpackingExample(**dict)Output
------
John Snow is a stark
Tywin is a lannister
Hodor is a hodor

Unpack the tuple as under →

unpackingExample(*tuple)Output
------
John Snow is a stark
Tywin is a lannister
Hodor is a hodor

The code for this post can be found in my GitHub repository here

--

--

satyabrata pal
ML and Automation

A QA engineer by profession, ML enthusiast by interest, Photography enthusiast by passion and Fitness freak by nature