Python Tutorial | Python tuples

Python Tuple
What You Will Learn:

What is tuple?

In Python programming, a tuple is similar to a list. The difference between the two is that we cannot change the elements of a tuple once it is assigned whereas, in a list, elements can be changed.

A tuple is a collection that is ordered and unchangeable. In Python, tuples are written with round brackets.

Advantages of Tuple over List

Since tuples are quite similar to lists, both of them are used in similar situations as well.
However, there are certain advantages of implementing a tuple over a list. Below listed are some of the main advantages:

* We generally use tuple for heterogeneous (different) data types and list for homogeneous (similar) datatypes.

* Since a tuple is immutable, iterating through a tuple is faster than with a list. So there is a slight performance boost.

* Tuples that contain immutable elements can be used as keys for a dictionary. With a list, this is not possible.

* If you have data that doesn’t change, implementing it as a tuple will guarantee that it remains write-protected.

Creating a Tuple

A tuple is created by placing all the items (elements) inside parentheses (), separated by a comma. The parentheses are optional but are a good practice to write them.
A tuple can have any number of items and they may be of different types (integer, float, list, string etc.).

# empty tuple
n = ()
print(n)

# Output:
()

# tuple having integers
n = (1, 2, 3)
print(n)

# Output:
(1, 2, 3)

# tuple with mixed datatypes
n = (1, “Hello”, 3.4)
print(n)

# Output:
(1, “Hello”, 3.4)

# nested tuple
n = (“mouse”, [8, 4, 6], (1, 2, 3))
print(n)

# Output:
(“mouse”, [8, 4, 6], (1, 2, 3))

Creating a tuple with one element is a bit tricky.

Having one element within parentheses is not enough. We will need a trailing comma to indicate that it is in fact a tuple.

# only parentheses is not enough

n = (“hello”)
print(type(n))

# Output:
<class ‘str’>

# need a comma at the end

n = (“hello”,)
print(type(n))

# Output:
<class ‘tuple’>

# parentheses is optional

n = “hello”,
print(type(n))

# Output:
<class ‘tuple’>

Visitor Counter

0051048