0% found this document useful (0 votes)
3 views3 pages

Python Tuple

A Python tuple is an immutable collection that maintains the order of elements and allows duplicates. Tuples are created using parentheses or the tuple() constructor, and items can be accessed using their index. The length of a tuple can be determined using the len() function.

Uploaded by

hananakamura699
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views3 pages

Python Tuple

A Python tuple is an immutable collection that maintains the order of elements and allows duplicates. Tuples are created using parentheses or the tuple() constructor, and items can be accessed using their index. The length of a tuple can be determined using the len() function.

Uploaded by

hananakamura699
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Python Tuple

A tuple is a collection similar to a Python list. The primary difference


is that we cannot modify a tuple once it is created.

Create a Python Tuple


We create a tuple by placing items inside parentheses ().
For example,
numbers = (1, 2, -5)
print(numbers)
Output: (1, 2, -5)

More on Tuple Creation


Create a Tuple Using tuple() Constructor

Tuple Characteristics
• Ordered - They maintain the order of elements.
• Immutable - They cannot be changed after creation.
• Allow duplicates - They can contain duplicate values.

Access Tuple Items


Each item in a tuple is associated with a number, known as a index.
The index always starts from 0, meaning the first item of a tuple is at
index 0, the second item is at index 1, and so on.
Index of Tuple Item
Access Items Using Index
We use index numbers to access tuple items. For example,
languages = ('Python', 'Swift', 'C++')

# access the first item


print(languages[0]) # Python

# access the third item


print(languages[2]) # C++

Tuple Cannot be Modified


Python tuples are immutable (unchangeable). We cannot add,
change, or delete items of a tuple.
If we try to modify a tuple, we will get an error. For example,
cars = ('BMW', 'Tesla', 'Ford', 'Toyota')
# trying to modify a tuple
cars[0] = 'Nissan' # error
print(cars)

Python Tuple Length


We use the len() function to find the number of items present in a
tuple. For example,
cars = ('BMW', 'Tesla', 'Ford', 'Toyota')
print('Total Items:', len(cars))

Output: Total Items: 4

You might also like