DEV Community

Srinivasulu Paranduru
Srinivasulu Paranduru

Posted on

Python : Part 5 - Tuples

  • Tuples are used to store multiple items in a single variable.
  • Tuple is one of 4 built-in data types in Python used to store collections of data, the other 3 are List, Set, and Dictionary, all with different qualities and usage.
  • A tuple is a collection which is ordered and unchangeable.

Tuples are written with round brackets.

thistuple = ("apple", "banana", "cherry")
print(thistuple)
Enter fullscreen mode Exit fullscreen mode
  • Tuple items are ordered, unchangeable, and allow duplicate values.
  • Tuple items are indexed, the first item has index [0], the second item has index [1] etc.

1.Tuples allow duplicate values:

thistuple = ("apple", "banana", "cherry", "apple", "cherry")
print(thistuple)
Enter fullscreen mode Exit fullscreen mode

2.Tuple Length

Print the number of items in the tuple

thistuple = ("apple", "banana", "cherry")
print(len(thistuple))
Enter fullscreen mode Exit fullscreen mode

3.Create Tuple With One Item: To create a tuple with only one item, you have to add a comma after the item, otherwise Python will not recognize it as a tuple.

thistuple = ("apple",)
print(type(thistuple))

#NOT a tuple
thistuple = ("apple")
print(type(thistuple))
Enter fullscreen mode Exit fullscreen mode

4.Tuple Items - Data Types
Tuple items can be of any data type:

tuple1 = ("apple", "banana", "cherry")
tuple2 = (1, 5, 7, 9, 3)
tuple3 = (True, False, False)
Enter fullscreen mode Exit fullscreen mode

5.A tuple can contain different data types:
Example:

# A tuple with strings, integers and boolean values:

tuple1 = ("abc", 34, True, 40, "male")
Enter fullscreen mode Exit fullscreen mode

6.The tuple() Constructor

Example:

Using the tuple() method to make a tuple:

thistuple = tuple(("apple", "banana", "cherry")) # note the double round-brackets
print(thistuple)
Enter fullscreen mode Exit fullscreen mode

Top comments (0)