A tuple is a collection of elements in Python, enclosed in parentheses and separated by commas. Tuples are similar to lists in that they can store multiple elements.
Some basic features of tuples are:
in keyword.len() function.Tuples are useful for representing fixed collections of items that should not be changed. They can store elements of any type, including other tuples, and can be indexed and sliced like lists.
You can create a tuple just like list. Here is an example of a tuple:
my_tuple = (1, "hello", 3.14)You can access the elements of a tuple by indexing, just like with a list:
print(my_tuple[0]) # prints 1
print(my_tuple[1]) # prints "hello"You can also use negative indexes to access elements from the end of the tuple:
print(my_tuple[-1]) # prints 3.14You can use the len() function to get the number of elements in a tuple:
print(len(my_tuple)) # prints 3You can use the in keyword to check if an element is in a tuple:
print("hello" in my_tuple) # prints TrueYou can use the + operator to concatenate two tuples:
new_tuple = my_tuple + (4, "world")
print(new_tuple) # prints (1, "hello", 3.14, 4, "world")You can unpack the values of a tuple into separate variables using the following syntax:
a,b,c = my_tuple
print(a) # 1
print(b) # "hello"
print(c) # 3.14You can also use tuple() method to convert other data types into tuple.
my_list = [1,2,3]
my_tuple = tuple(my_list)
print(my_tuple) # (1,2,3)You can use the del keyword to delete a tuple:
del my_tupleYou can use the * operator to repeat a tuple a certain number of times:
my_tuple = (1, 2)
print(my_tuple * 3) # prints (1, 2, 1, 2, 1, 2)You can use slicing to extract a specific sub-sequence from a tuple:
my_tuple = (1, 2, 3, 4, 5)
print(my_tuple[1:3]) # prints (2, 3)These are some of the basic concepts of working with tuples in Python. As a beginner, it is important to practice using tuples and become familiar with their syntax and usage.