Define tuple in python - how indexing and splitting done in tuple?

Introduction

Python is a popular high-level programming language that supports various data types, including lists, dictionaries, and tuples. In this article, we will discuss tuples in Python, how they are defined, and how indexing and splitting is done in tuples.

Defining a Tuple

A tuple is a collection of values that are ordered and immutable. Tuples are defined using parentheses (), and the values are separated by commas. Here is an example of a tuple that contains three values:

my_tuple = (1, "Hello", 3.14)

Tuples are similar to lists, but they are immutable, which means that once a tuple is defined, its values cannot be changed. Tuples are often used to store related values that are not meant to be modified.

Indexing in Tuple

Indexing is a way to access individual values in a tuple. In Python, indexing starts from 0, which means that the first value in a tuple has an index of 0, the second value has an index of 1, and so on. To access a value in a tuple, we can use square brackets [] and provide the index of the value that we want to access. Here is an example of indexing a tuple:

my_tuple = (1, "Hello", 3.14)
print(my_tuple[0])   # Output: 1
print(my_tuple[1])   # Output: Hello
print(my_tuple[2])   # Output: 3.14

Splitting a Tuple

Tuples can also be split into multiple values using the unpacking operator (*). To split a tuple, we can assign the values to multiple variables, and the unpacking operator will assign the remaining values to the last variable. Here is an example of splitting a tuple:

my_tuple = (1, "Hello", 3.14)
a, b, c = my_tuple
print(a)    # Output: 1
print(b)    # Output: Hello
print(c)    # Output: 3.14

In this example, we assign the values of the tuple to the variables a, b, and c. The unpacking operator (*) is used to assign the remaining values to the last variable, which is c in this case.

Conclusion

In this article, we discussed tuples in Python, how they are defined, and how indexing and splitting is done in tuples. Tuples are immutable collections of ordered values that are defined using parentheses (). Indexing is used to access individual values in a tuple using square brackets [], and the first value has an index of 0. Tuples can also be split into multiple values using the unpacking operator (*), which assigns the remaining values to the last variable. By following this article, you should now have a good understanding of tuples in Python and how they can be used in your code.

Advertisements

Next Post: Hardware and software requirement of voice assistant AI and Python
Previous Post: Write a code in Python to input 4 digit number and reverse its first and last digit

Comments