Master Python Tuples: Definition, Indexing, Slicing, and Modification Tricks
This article explains Python tuples, covering their definition, creation syntax, single‑element nuances, indexing and slicing behavior, and how to modify values indirectly by converting to a list, complete with code examples and visual illustrations.
What is a tuple?
An ordered collection called a tuple. It is similar to a list but immutable after creation.
Usage
1. Defining a tuple
Tuples use parentheses, while lists use square brackets. Elements are separated by commas.
tup1 = ('361way', 'com', 1997, 2000)
print(type(tup1))
tup2 = (1, 2, 3, 4, 5)
tup3 = "a", "b", "c", "d"
print(type(tup3))Even without parentheses, a comma‑separated sequence is a tuple. For a single‑element tuple, a trailing comma is required; otherwise the value is interpreted as the element’s type.
tup1 = (111)
print(type(tup1))
tup1 = ("abc")
print(type(tup1))
tup1 = ("abc",)
print(type(tup1))An empty tuple is created with empty parentheses.
tup1 = ()
print(type(tup1))2. Indexing and slicing
Tuples support indexing and slicing just like strings and lists.
tup1 = ('361way', 'com', 2013, 2014)
print(tup1[0])
# print(tup1[4]) # raises IndexError
tup2 = (1, 2, 3, 4, 5, 6, 7)
print(tup2[1:5])Retrieving a single element returns its original type; slicing returns a new tuple.
3. Modifying tuple values
Elements cannot be deleted or changed directly. The whole tuple can be removed with del.
tup1 = ('361way', 'com', 2013, 2014)
# del tup1[3] # raises TypeError
# tup1[3] = 'abc' # raises TypeError
del tup1 # deletes the entire tupleTo modify values, convert the tuple to a list, change the list, then convert back.
tup1 = ('361way', 'com', 2013, 2014)
list1 = list(tup1)
print(list1)
list1[3] = 'change'
print(list1)
tup1 = tuple(list1)
print(tup1)Note that after conversion, the new tuple has a different memory address (verified with id()).
Summary
The article provides a comprehensive guide to Python tuples, covering definition, creation, single‑element nuances, indexing, slicing, and a workaround for modifying values via list conversion, illustrated with code snippets and images.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Python Crawling & Data Mining
Life's short, I code in Python. This channel shares Python web crawling, data mining, analysis, processing, visualization, automated testing, DevOps, big data, AI, cloud computing, machine learning tools, resources, news, technical articles, tutorial videos and learning materials. Join us!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
