IKH

Tuple Comprehensions

  • Tuple Comprehension is not supported by Python. If you try to create we are not getting tuple object and we are getting generator object.

Example

Python
t= ( x**2 for x in range(1,6))
print(type(t))
for x in t:
  print(x)

Output

PowerShell
<class 'generator'>
1
4
9
16
25

Question

Write a program to take a tuple of numbers from the keyboard and print its sum and average

Python
t=eval(input("Enter Tuple of Numbers:"))
l=len(t)
sum=0
for x in t:
  sum=sum+x
print("The Sum=",sum)
print("The Average=",sum/l)

Output

PowerShell
Enter Tuple of Numbers:(10,20,30,40)
The Sum= 100
The Average= 25.0

Tuple Packing and Unpacking

  • We can create a tuple by packing a group of variables.

Example

Python
a=10
b=20
c=30
d=40
t=a,b,c,d
print(t)

Output

Python
10,20,30,40)
  • Here a,b,c,d are packed into a tuple t. This is nothing but tuple packing.
  • Tuple unpacking is the reverse process of tuple packing. We can unpack a tuple and assign its values to different variables.

Example

Python
t=(10,20,30,40)
a,b,c,d=t
print("a=",a,"b=",b,"c=",c,"d=",d)

Output

Python
a= 10 b= 20 c= 30 d= 40

Note

  • At the time of tuple unpacking the number of variables and number of values should be same, Otherwise we will get ValueError.

Example

Python
t=(10,20,30,40)
a,b,c=t

Output

Python
 ValueError: too many values to unpack (expected 3)

Differences between List and Tuple

  • List and Tuple are exactly same except list objects are mutable where as tuple objects are immutable.
  • In both cases insertion order is preserved, duplicate objects are allowed, heterogeneous objects are allowed, index and slicing are supported.

Ungraded Questions

Get ready for an exhilarating evaluation of your understanding! Brace yourself as we dive into the upcoming assessment. Your active participation is key, so make sure to attend and demonstrate your knowledge. Let’s embark on this exciting learning journey together!


Name
Email
Phone

Report an error