Tuple

Tuple is the data structures in Python which is used to store multiple items within a single variable. These multiple items can be of same or different data type.

Tuples are:

  1. Unchangeable - we can not change, add, or remove the items of a list.
  2. Ordered - items in a list have a definite order which does not changes.
  3. Indexing - tuple items have indexes. First element has 0 index, second has 1 and so on.
  4. Redundant Data - items of a tuple can be repeated.

Members of a List

Members of a tuple are unchangeable. We can also calculate the number of items in our tuple.

Data types of members of tuple

Members of a tuple can be of any data type. They can have same or different data types.

Repetition

Members of a tuple can be repeated multiple times.

Tuple with one member

Tuple with one member is a string. You can check the data type using type() function.

Access Tuple Items

We can access the items of a tuple using indexes.

Range of Indexes

We can access the range of items in a tuple. We have to specify the starting and the ending index.

Negative Indexes

Negative indexes start from the end of the tuple. index -1 corresponds to the last element. -2 index corresponds to the second last index. -3 index corresponds to the third last index. The element at last index is not printed.

Range of Negative Indexes

We have to specify the range of negative indexes. We have to specify starting and the ending index. The element at last index is not printed.

Update items of Tuple

Tuples are unchangeable. It means that you can not update the items of tuple once it is created. But as we can convert tuple to list, update items and convert list back to tuple.

Note: We can convert tuple to list and can apply list methods and can convert lists back to tuple. You can study about list methods in previous section.

Packing a Tuple

When we assign values to a tuple, it is called packing a tuple.

Unpacking a Tuple

Assigning values of tuple back to variables is called unpacking a tuple.

Using Asterisk

If the number of items of tuple is more than the number of variables, we use asterisks to assign all the remaining values to the variable with asterisks.

Joining Tuples

We can join two tuples using "+" operator.

Count method

We can count items in a tuple using count method.

Index method

We can get the index of item using index method.

Practice Exercises

Complete these exercises to reinforce your learning and earn XP

Sign in to track your progress and earn XP!
Exercise 1 of 2Easy

Which of the following is a best practice in programming?

10 XP~2 min
Exercise 2 of 2Easy

Code that is easy to read and understand is called ___ code.

10 XP~2 min