Tuples unpacking in Python

 

Tuples:

my_tup = [(1,2),(2,3),(4,5),(6,7),(8,9)]

for tup in my_tup:

    print(tup)


Output:

(1, 2)
(2, 3)
(4, 5)
(6, 7)
(8, 9)

Tuple unpacking methods:

Method-1: using (a,b) 

my_tup = [(1,2),(2,3),(4,5),(6,7),(8,9)]

for a,b in my_tup:
    print(a)
    print(b)

Output:

1
2
2
3
4
5
6
7
8
9


Dictionaries:

my_dict = {'Apple':2, 'Grapes':1, 'Orange':1 }

for dict in my_dict:
    print(dict)

Output:

Apple
Grapes
Orange

Note: By default, it prints only the Keys but not the values.

To print both the keys and pairs we have to use items() 
like 
my_dict.items()
my_dict.values()

my_dict = {'Apple':2, 'Grapes':1, 'Orange':1 }

for dict in my_dict.items():
    print(dict)
 
Output:

('Apple', 2)
('Grapes', 1)
('Orange', 1)

Again Here you could use tuple unpacking technique.

my_dict = {'Apple':2, 'Grapes':1, 'Orange':1 }

for key,value in my_dict.items():
    print(key)
    print(value)

Output:

Apple
2
Grapes
1
Orange
1







Comments

Popular posts from this blog

Tuples in Python

Auditing in Oracle database

Boolean in Python