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 9Dictionaries:my_dict = {'Apple':2, 'Grapes':1, 'Orange':1 } for dict in my_dict: print(dict)Output:Apple Grapes OrangeNote: By default, it prints only the Keys but not the values.To print both the keys and pairs we have to use items()likemy_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
Post a Comment