What does *tuple and **dict mean in Python
If you want to learn tuples and dict in Python programming.
What does mean by *tuple?
Tuple – The tuple contains the group of elements which can be the same or different types:-
- A tuple is occupied less memory wrt the list.
- Tuples are represented using parentheses ( ).
Ex:- a = (21, 23, 27, 30, ‘CodeSpeedy’)
1. Creating Empty Tuple
If you want to create an empty tuple using below this syntax.
Syntax:- tuple_name = ( )
Ex:- a = ( )
2.Creating Tuple
If you Want to create tuple by using an elements separated by the , (commas) inside the parentheses you can see below the example ⇓.
⇒With one Element
b = (17) ⇐ It will become integer
c = (25, )
⇒With Multiple Elements
d = (11, 17, 19, 27)
e = (11, 17, 19, 27,’CodeSpeedy’)
f = 11, 23, -55, 21.7, ‘CodeSpeedy’
⇒Index
The index is represented by the using position number of a tuple’s element. The index is starts from 0 onwards and is used inside this braces [ ].
Ex:- a = (11, 23, -55, 21.7, ‘CodeSpeedy’)
⇒Accessing Tuple’s Element
a = (11, 23, -55, 21.7, ‘CodeSpeedy’)
print(a[0])
print(a[1])
print(a[2])
print(a[3])
print(a[4])
Code:-
# Tuple
# Creating Empty Tuple
a = () #integer
# Creating Tuple with one element
b = (11)
c = (25,)
# Creating Tuple with Multiple element
d = (11, 23, 35, 47)
e = (11, 23, -55, 21.7, 'CodeSpeedy')
f = 11, 23, -55, 21.7, 'CodeSpeedy' # e and f are same
print()
# Access using index:-
print("Accessing Tuple d:")
print("d[0] =", d[0])
print("d[1] =", d[1])
print("d[2] =", d[2])
print("d[3] =", d[3])
print()
print("Accessing Tuple e:")
print("e[0] =", e[0])
print("e[1] =", e[1])
print("e[2] =", e[2])
print("e[3] =", e[3])
print("e[4] =", e[4])
print()
print("Accessing Tuple f:")
print("f[0] =", f[0])
print("f[1] =", f[1])
print("f[2] =", f[2])
print("f[3] =", f[3])
print("f[4] =", f[4])
OutPut:-
Accessing Tuple d: d[0] = 11 d[1] = 23 d[2] = 35 d[3] = 47 Accessing Tuple e: e[0] = 11 e[1] = 23 e[2] = -55 e[3] = 21.7 e[4] = CodeSpeedy Accessing Tuple f: f[0] = 11 f[1] = 23 f[2] = -55 f[3] = 21.7 f[4] = CodeSpeedy
What does mean by *dict?
*dict( ) Function:-
This function creates a new dictionary. This can be also used in type casting to convert iterable to dict.
Syntax:– dict(**keywors_arguments)
Code:-
# Dictionary Comprehension
lst = [(103, "Code"), (102, "Speedy")]
dict = {s:v for s,v in lst}
print(dict)
OutPut:-
{103: 'Code', 102: 'Speedy'}
.With and without Dict.
# Without Dict Comprehension
dict = {}
for n in range(13):
dict[n]=n*3
print(dict)
# With DIct Comprehension
dictX = {n:n*3 for n in range(13)}
print(dictX)
OutPut:-
{0: 0, 1: 3, 2: 6, 3: 9, 4: 12, 5: 15, 6: 18, 7: 21, 8: 24, 9: 27, 10: 30, 11: 33, 12: 36}
{0: 0, 1: 3, 2: 6, 3: 9, 4: 12, 5: 15, 6: 18, 7: 21, 8: 24, 9: 27, 10: 30, 11: 33, 12: 36}
Leave a Reply