Python Tutorial– Tuples Introduction

Python Exercise Lists

Tuples are another important sequence structure in Python. Similar to lists, tuples are composed of a series of elements ordered in a specific order.

Tuples differ from lists in that:

  • The elements of the list can be changed, including modifying element values, deleting and inserting elements, so the list is a mutable sequence;
  • Once a tuple is created, its elements cannot be changed, so tuples are immutable sequences.

Tuples can also be viewed as immutable lists. Generally, tuples are used to hold content that does not need to be modified.

Formally, all elements of the tuple are enclosed in a pair of parentheses (), and adjacent elements are separated by commas, as shown below:

(element1, element2, ..., elementn)

Where element1 ~ elementn represents each element in the tuple, the number is not limited, as long as it is a data type supported by Python.

From the perspective of storage content, tuples can store any type of data such as integers, real numbers, strings, lists, and tuples. In the same tuple, the types of elements can be different, for example:

("", 1, [2, 'a'], ("abc", 3.0))

In this tuple, there are multiple types of data, including integers, strings, lists, and tuples. In addition, we all know that the data type of a list is list, so what is the data type of a tuple? Let's take a look at the type function:

type(("", 1, [2, 'a'], ("abc", 3.0)))

The output is:


Python - Create Tuples

Python provides two methods for creating tuples, one by one.

1) Create directly using ()

After creating a tuple through (), you generally use = to assign it to a variable, the specific format is:

tuplename = (element1, element2, ..., elementn)

Among them, tuplename represents the variable name, and element1 ~ elementn represent the elements of the tuple. For example, the following tuples are all legal:

num = (17, 23, 51, 88, 25)
course = ("Python Tutorial", "")
abc = ("Python", 19, [1,2], ('c', 2.0))

In Python, tuples are usually surrounded by a pair of parentheses, but parentheses are not required. As long as each element is separated by a comma, Python will treat it as a tuple. example of:

course = "Python Tutorial", ""
print (course)

The output is:

('Python Tutorial', '')

One thing to note is that when there is only one element of type string in the created tuple, the element must be followed by a comma, otherwise the Python interpreter will treat it as a string. Look at the following code:

# Finally add a comma
a = ("",)
print (type (a))
print (a)
#No commas at the end
b = ("")
print (type (b))
print (b)

The output is:

[class 'tuple']
[class 'str']

You see, only the variable a is a tuple, and the following variable b is a string.

2) Create tuples using the tuple function

In addition to using [] to create tuples, Python provides a built-in function tuple () to convert other data types to tuple types. The syntax of tuple () is as follows:

tuple (data)

Among them, data represents data that can be converted into tuples, including strings, tuples, and range objects. tuple () usage example:

#Convert string to tuple
tup_1 = tuple ("Python")
print (tup_1)
#Convert the list into a tuple
list_1 = name = ["Jason", "Alice", "Mark"]
tup_2 = tuple (list_1)
print (tup_2)
#Convert dictionary to tuple
dict_1 = {'a': 99, 'b': 82, 'c': 2}
tup_3 = tuple (dict_1)
print (tup_3)
#Convert interval to tuple
range_1 = range (1, 6)
tup_4 = tuple (range_1)
print (tup_4)
#Create empty tuple
print (tuple ())

The output is:

('P', 'y', 't', 'h', 'o', 'n')
('Jason', 'Alice', 'Mark')
('a', 'b', 'c')
(1, 2, 3, 4, 5)

Python - Access Tuple Elements

As with lists, we can use an index to access an element in a tuple (getting the value of an element), or we can use a slice to access a group of elements in the tuple (getting a new child) group). The format for accessing tuple elements using an index is:

tuplename [i]

Among them, tuplename represents the tuple name, and i represents the index value. The index of a tuple can be positive or negative. The format for accessing tuple elements using slices is:

tuplename [start: end: step]

Among them, start represents the start index, end represents the end index, and step represents the step size. The above two methods have been explained in the "Python sequence", so I won't repeat them here, just for example demonstration, please see the following code:

website= tuple ("")
#Access an element in a tuple using an index
print (website [3]) #Use positive index
print (website [-4]) #Use negative index
#Access a set of elements in a tuple using a slice
print (website [8: 18]) #Use positive slice
print (website [8: 18: 2]) #Specify the step size
print (website [-5: -1]) #Use negative slice

The output is:

('l', 'e', 'a', 'r', 'n', 'i', 'n', 'g', 'p', 'o')
('l', 'a', 'n', 'n', 'p')
('s', '.', 'c', 'o')

Python - Tuple Modification

As we mentioned earlier, tuples are immutable sequences, and the elements in a tuple cannot be modified, so we can only create a new tuple to replace the old tuple. For example, to reassign a tuple variable:

tup = (99, 0.3, -88, 72)
print (tup)
#Reassign tuples
tup = ("Python", "")
print (tup)

The output is:

(99, 0.3, -88, 72)
('Python', '')

In addition, you can also add new elements to the tuple by connecting multiple tuples (using + to stitch the tuples), for example:

tup_1 = (99, 0.3, -88, 72)
tup_2 = (-52.8, 2+12j, 99)

The output is:

(99, 0.3, -88, 72, -52.8, (2+12j), 99)
(99, 0.3, -88, 72)
(-52.8, (2+12j), 99)

You see, after using + stitching tuples, the contents of tup_1 and tup_2 cannot be changed, which indicates that a new tuple is generated.

Python - Remove Tuples

When the created tuple is no longer used, you can delete it with the del keyword, for example:

tup = ("Python", "")
del tup

The output is:

('Python', '')
NameError         Traceback (most recent call last)
[ipython-input-25-6e7b3c328f18] in [module]
2 print(tup)
3 del tup
----> 4 print(tup)
NameError: name 'tup' is not defined

Python's built-in garbage collection function automatically destroys unused tuples, so generally you don't need to manually delete through del.


More Tutorials:

Python Installation - Linux (Ubuntu)
Python Installation - Mac OS
Integrated Development Environment - IDE
Python - Basic Variables
Python - Sequence Introduction
Python - Output Formatting
Python - Escape Character
Python - Type Conversion
Python - Numbers
Python – Arithmetic Operators
Python – Assignment Operators
Python – Comparison Operators
Python – Logical Operators
Python – Precedence and Associativity Operators
Python – Bytes Type and Usage
Python – Long & Raw Strings
Python – Concatenate Function
Python – Slice Function
Python – Length and Split Function
Python – Join and Count Function
Python – Find Function
Python – Index Function
Python – Alignment Function
Python – Startswith and Endswith Function
Python – String Case Conversion
Python – Remove Specified Character
Python – Encode and Decode Function
Python – dir and help Function
Python – Input Output Introduction
Python – Basic Operation
Python – Open Function
Python – Read Function
Python – Readline Function
Python – Write Function
Python – Close Function
Python – Seek and Tell Function
Python – Pickle Module
Python - File Input Module and Linecache Module
Python - Pathlib Module
Python - Pathlib Module
Python - os.path Module
Python - fnmatch Module
Python - Tuple Introduction
Python - List Introduction
Python - List Add Element
Python - List Delete Element
Python - List Modification Element
Python - List Find Element
Python - Dictionary Introduction
Python - Dictionary Basic Operation
Python - Dictionary Method Guide
Python - Set Collection
Python - Set Basic Operation
Python - Set Basic Method
Python - Frozenset Method
Python - If Condition I
Python - If Condition II
Python - While loop
Python - For loop
Python - Pass Statement
Python - Break Statement
Python - Zip Reverse Function
Python - Function Introduction
Python - Positional Parameters
Python - Key Arguments
Python - None and Return
Python - Variable Scope
Python - Local Function
Python - Closure Method
Python - Lamdba Expression

More Python Exercises:

Python String Exercises
Python List Exercises
Python Library Exercises
Python Sets Exercises
Python Array Exercises
Python Condition Statement Exercises