Python Tuples
A Tuple is a sequence of values like list data type. But the main difference between lists and tuples is that tuples are immutable. You can not modify, append or remove the values of tuple. Another difference is that tuples are used with parentheses instead of square bracket. For example:
tuple1 = ("c", "python", "java", "javascript")
Same as lists the string values of tuples are also typed with quote characters to mark where the string begins and ends. The tuple indices also start with 0. The items have to be the same type. A tuple can contain a string, a float, an integer and other data types also. For example:
tuple1 = ("python", 7, 3.75, True, None)
Accessing Tuple Items
You can access the tuple items by referring to the index number.
Example:
tuple1 = ("python", 7, 3.75, True, None)
print(tuple1[0])
print(tuple1[3])
Output:
python True
Just an index can get a single value from a tuple but by specifyling a range you can get several values from a tuple.
Example:
tuple1 = ("python", 7, 3.75, True, None)
print(tuple1[0:3])
print(tuple1[1:4])
Output:
('python', 7, 3.75) (7, 3.75, True)
You can also ignore one or both of the indices on either side of the colon. Ignore the first side is just same as using 0 and ignore the right side will give the value to the end of the tuple.
Example:
tuple1 = ("python", 7, 3.75, True, None)
print(tuple1[:3])
print(tuple1[1:])
Output:
('python', 7, 3.75) (7, 3.75, True)
Tuple Concatenation
You can concatenate two tuples using the + operator. It combines two tuples into a new tuple.
Example:
tuple1 = ("c", "python", "java")
tuple2 = (1, 2, 3)
tuple3 = tuple1 + tuple2
print(tuple3)
Output:
('c', 'python', 'java', 1, 2, 3)
Removing Tuple
You can not add or remove items of a tuple but you can delete a complete tuple using del keyword.
Example:
tuple1 = ("c", "python", "java")
del tuple1
print(tuple1)
Output:
Traceback (most recent call last): File "C:\Users\Hp\Desktop\py\python.py", line 3, in <module> print(tuple1) NameError: name 'tuple1' is not defined
Note: Since the total tuple is deleted an error is raised in the output.
Converting Types with list() and tuple() Functions
The list() and tuple() functions will return list and tuple versions of the values passed to them.
Example:
a = ["python", 7, 3.75, True, None]
b = tuple(a)
print(b)
x = ("python", 7, 3.75, True, None)
y = list(x)
print(y)
Output:
('python', 7, 3.75, True, None) ['python', 7, 3.75, True, None]
Length of a Tuple
You can define the length of a tuple using the len() method.
Example:
tuple1 = ("c", "python", "javascript", "java")
print(len(tuple1))
Output:
4
Tuple Methods
There are a set of built-in methods in python which you can use on lists.
Method | Description |
---|---|
count() | Returns the number of items with the specified value |
index() | Returns the position at the first occurrence with the specified value |