Python is an object-oriented programming language ideally designed for rapid prototyping of complex applications. Like Perl, Python source code is also available under the GNU General Public License (GPL).

In this article we will see Packing and Unpacking in Python for list, tuples and dictionaries with example.

1) Packing and Unpacking with python lists?

In packing, we place value into a new list while in unpacking we extract those values back into variables from the list.
# packing and unpacking in list
lis = ["Tech", 20, "Site"] 
[name, age, type] = lis
print name
print age
print type
Output: Output will be something like this:

Tech
20
Site


2) Packing and Unpacking with python tuples?

In packing, we place value into a new tuple while in unpacking we extract those values back into variables from the tuple.
# packing and unpacking in tuples
tup = ("Tech", 20, "Site")
(name, age, type) = tup
print name
print age
print type
Output: Output will be something like this:

Tech
20
Site


3) Packing and Unpacking with python dictionaries?

In packing, we place value into a new dictionary while in unpacking we extract those values back into variables from the dictionary.
# packing and unpacking in dictionaries
dict = {'k1':'Tech','k2':'Site'}
[name, type] = dict
print dict[name]
print dict[type]
Output: Output will be something like this:

Site
Tech


4) Packing and Unpacking in python argument passing?

Packing and Unpacking in python's functions argument passing is done using "*" for lists and tuples and with "**" for dictionaries.

4.1) Packing

def printSum(*args):
	sum =0
	for i in range(0, len(args)):
		sum=sum+args[i]
	return sum

#tupple
print(printSum(1, 2, 3))
Output: Output will be something like this:

Site
Tech


4.2) Unpacking in list and tuple

#Unpacking
def printSum(a,b,c):
	return a+b+c

#tupple
tup = (1, 2, 3);
print(printSum(*tup))

#list
lis = [1, 2, 3];
print(printSum(*lis))
Output: Output will be something like this:

6
6


4.3) Unpacking in dictionaries

#unpacking
def printSum(a,b,c):
	return a+b+c

#dictionary
dict = {'a':1,'b':2,'c':3}
print(printSum(**dict))
Output: Output will be something like this:

6


In this article we have seen, Packing and Unpacking in Python for list, tuples and dictionaries with example. In upcoming articles we will see more complex usecases and tricks of python.
  • By Techburps.com
  • Sep 30, 2017
  • Python