Python

Tuple-Immutable list in Python

We provide effective and economically affordable online training courses for R and Python, click here for more details and course registration !

Python object tuple is a type of list in which the elements can not be modified. It is immutable. When the elements are stored information that are stable, like the area of countries, values of genders, you can use tuples. Tuples are created using parentheses. In the following code, two tuples representing countries and their corresponding areas are created.


#create two tuples
countries = ('USA','Russia','China')
areas= (940,1920,960)
#show tuples
countries
#output
('USA', 'Russia', 'China')
areas
#output
(940, 1920, 960)

Elements of a tuple can be indexed using brackets, same as for a list. But the element can not be modified using indexing method.

#indexing a tuple
#return the first element of a tuple
countries[0]
#output
'USA'
#return the first two elements of a tuple
areas[:2]
#output
(940, 1920)
#trying to modify value of a tuple
countries[2] = 'Japan'
#output 
TypeError: 'tuple' object does not support item assignment

Tuple can be operated with for loop, same as for list.

#for loop with a tuple
for area in areas:
    print(area)
#output 
940
1920
960

Although a tuple is immutable, the values can be changed by re-creating a tuple with the same name of the existing one.


#re-create a tuple with new values
countries = ('Japan','Russia','Mongolia')
#print tuple
countries
#output 
('Japan', 'Russia', 'Mongolia')

For getting more knowledge of Python and a preview of our training course, you can watch Python tutorial videos on our YouTube channel !

wilsonzhang746

Recent Posts

affine_grid() in pytorch

According to PyTorch document, In PyTorch, torch.nn.functional.affine_grid generates a 2D or 3D flow field (sampling…

3 weeks ago

How to create an Android mobile app with a deep learning AI model ?

Creating an Android mobile app with a deep learning AI model involves several key steps:…

10 months ago

Download source files for R Machine learning

Click here to go to source files for R Machine Learning

11 months ago

Python Machine Learning Source Files

Click here to download Python Machine Learning Source Files !

12 months ago

Install PyTorch on Windows

PyTorch is a deep learning package for machine learning, or deep learning in particular for…

1 year ago

Topic Modeling using Latent Dirichlet Allocation with Python

Topic modeling is a subcategory of unsupervised machine learning method, and a clustering task in…

1 year ago