Creating Tuples:
You can create a tuple by enclosing a sequence of elements within parentheses ().
tuple1 = (1, 2, 3)
tuple2 = ('a', 'b', 'c')
mixed_tuple = (1, 'hello', 3.14)
#clcoding.com
Accessing Elements:
You can access elements of a tuple using indexing, just like with lists.
tuple1 = (1, 2, 3)
print(tuple1[0])
print(tuple1[1])
#clcoding.com
1
2
Iterating over Tuples:
Tuple Methods:
Immutable Nature:
Once a tuple is created, you cannot modify its elements.
tuple1 = (1, 2, 3)
# This will raise an error
tuple1[0] = 4
#clcoding.com
Tuple Unpacking:
You can unpack a tuple into individual variables.
tuple1 = ('apple', 'banana', 'cherry')
a, b, c = tuple1
print(a)
print(b)
print(c)
#clcoding.com
apple
banana
cherry
Returning Multiple Values from Functions:
Functions in Python can return tuples, allowing you to return multiple values.
def get_coordinates():
x = 10
y = 20
return x, y
x_coord, y_coord = get_coordinates()
print("x coordinate:", x_coord)
print("y coordinate:", y_coord)
#clcoding.com
x coordinate: 10
y coordinate: 20
Iterating over Tuples:
You can iterate over the elements of a tuple using a loop.
tuple1 = ('apple', 'banana', 'cherry')
for fruit in tuple1:
print(fruit)
#clcoding.com
apple
banana
cherry
0 Comments:
Post a Comment