Python Tuple Data
A tuple is a collection of data that is ordered and unchangeable. In Python, tuples are written with round brackets. For example, my_tuple = (1, 2, 3) is a tuple with three elements. You can access the elements of a tuple by using indexing or slicing. For example, my_tuple[0] returns 1 and my_tuple[1:3] returns (2, 3). You can also use some methods on tuples such as count() and index(). For example, my_tuple.count(2) returns how many times 2 appears in the tuple and my_tuple.index(3) returns the position of 3 in the tuple. Tuples are useful for storing data that does not change and for packing and unpacking values.
Here are some examples of Python code using tuples:
# Creating a tuple
fruits = ("apple", "banana", "cherry")
# Accessing a tuple element
print(fruits[1]) # prints banana
# Slicing a tuple
print(fruits[-2:]) # prints ("banana", "cherry")
# Looping through a tuple
for fruit in fruits:
print(fruit)
# Checking if an element is in a tuple
if "apple" in fruits:
print("Yes")
# Finding the length of a tuple
print(len(fruits)) # prints 3
# Counting how many times an element appears in a tuple
print(fruits.count("apple")) # prints 1
# Finding the position of an element in a tuple
print(fruits.index("cherry")) # prints 2
# Packing and unpacking tuples
a = 10
b = 20
c = (a, b) # packing
x, y = c # unpacking
print(x) # prints 10
print(y) # prints 20
If you have any questions about this code, you can drop a line in comment.
Comments
Post a Comment