Python Tuples

A comma-separated group of items is called a Python triple. The ordering, settled items, and reiterations of a tuple are to some degree like those of a rundown, but in contrast to a rundown, a tuple is unchanging.

The main difference between the two is that we cannot alter the components of a tuple once they have been assigned. On the other hand, we can edit the contents of a list.

Example

Features of Python Tuple

  • Tuples are an immutable data type, meaning their elements cannot be changed after they are generated.
  • Each element in a tuple has a specific order that will never change because tuples are ordered sequences.

Forming a Tuple:

All the objects-also known as "elements"-must be separated by a comma, enclosed in parenthesis (). Although parentheses are not required, they are recommended.

Any number of items, including those with various data types (dictionary, string, float, list, etc.), can be contained in a tuple.

Code

Output:

Empty tuple:  ()
Tuple with integers:  (4, 6, 8, 10, 12, 14)
Tuple with different data types:  (4, 'Python', 9.3)
A nested tuple:  ('Python', {4: 5, 6: 2, 8: 2}, (5, 3, 5, 6))

Parentheses are not necessary for the construction of multiples. This is known as triple pressing.

Code

Output:

(4, 5.7, 'Tuples', ['Python', 'Tuples'])
<class 'tuple'>
<class 'TypeError'>

The development of a tuple from a solitary part may be complex.

Essentially adding a bracket around the component is lacking. A comma must separate the element to be recognized as a tuple.

Code

Output:

<class 'str'>
<class 'tuple'>
<class 'tuple'>

Accessing Tuple Elements

A tuple's objects can be accessed in a variety of ways.

Indexing

Indexing We can use the index operator [] to access an object in a tuple, where the index starts at 0.

The indices of a tuple with five items will range from 0 to 4. An Index Error will be raised assuming we attempt to get to a list from the Tuple that is outside the scope of the tuple record. An index above four will be out of range in this scenario.

Because the index in Python must be an integer, we cannot provide an index of a floating data type or any other type. If we provide a floating index, the result will be TypeError.

The method by which elements can be accessed through nested tuples can be seen in the example below.

Code

Output:

Python
Tuple
tuple index out of range
tuple indices must be integers or slices, not float
l
6
  • Negative Indexing

Python's sequence objects support negative indexing.

The last thing of the assortment is addressed by - 1, the second last thing by - 2, etc.

Code

Output:

Element at -1 index:  Collection
Elements between -4 and -1 are:  ('Python', 'Tuple', 'Ordered')

Slicing

Tuple slicing is a common practice in Python and the most common way for programmers to deal with practical issues. Look at a tuple in Python. Slice a tuple to access a variety of its elements. Using the colon as a straightforward slicing operator (:) is one strategy.

To gain access to various tuple elements, we can use the slicing operator colon (:).

Code

Output:

Elements between indices 1 and 3:  ('Tuple', 'Ordered')
Elements between indices 0 and -4:  ('Python', 'Tuple')
Entire tuple:  ('Python', 'Tuple', 'Ordered', 'Immutable', 'Collection', 'Objects')

Deleting a Tuple

A tuple's parts can't be modified, as was recently said. We are unable to eliminate or remove tuple components as a result.

However, the keyword del can completely delete a tuple.

Code

Output:

'tuple' object does not support item deletion
name 'tuple_' is not defined

Repetition Tuples in Python

Code

Output:

Original tuple is:  ('Python', 'Tuples')
New tuple is:  ('Python', 'Tuples', 'Python', 'Tuples', 'Python', 'Tuples')

Tuple Methods

Like the list, Python Tuples is a collection of immutable objects. There are a few ways to work with tuples in Python. With some examples, this essay will go over these two approaches in detail.

The following are some examples of these methods.

  • Count () Method

The times the predetermined component happens in the Tuple is returned by the count () capability of the Tuple.

Code

Output:

Count of 2 in T1 is: 5
Count of java in T2 is: 2

Index() Method:

The Index() function returns the first instance of the requested element from the Tuple.

Parameters:

  • The thing that must be looked for.
  • Start: (Optional) the index that is used to begin the final (optional) search: The most recent index from which the search is carried out
  • Index Method

Code

Output:

First occurrence of 1 is 2
First occurrence of 1 after 4th index is: 6

Tuple Membership Test

Utilizing the watchword, we can decide whether a thing is available in the given Tuple.

Code

Output:

True
False
False
True

Iterating Through a Tuple

A for loop can be used to iterate through each tuple element.

Code

Output:

Python
Tuple
Ordered
Immutable

Changing a Tuple

Tuples, instead of records, are permanent articles.

This suggests that once the elements of a tuple have been defined, we cannot change them. However, the nested elements can be altered if the element itself is a changeable data type like a list.

Multiple values can be assigned to a tuple through reassignment.

Code

Output:

'tuple' object does not support item assignment
('Python', 'Tuple', 'Ordered', 'Immutable', [1, 2, 10, 4])
('Python', 'Items')

The + operator can be used to combine multiple tuples into one. This phenomenon is known as concatenation.

We can also repeat the elements of a tuple a predetermined number of times by using the * operator. This is already demonstrated above.

The aftereffects of the tasks + and * are new tuples.

Code

Output:

('Python', 'Tuple', 'Ordered', 'Immutable', 4, 5, 6)

Tuples have the following advantages over lists:

  • Triples take less time than lists do.
  • Due to tuples, the code is protected from accidental modifications. It is desirable to store non-changing information in "tuples" instead of "records" if a program expects it.
  • A tuple can be used as a dictionary key if it contains immutable values like strings, numbers, or another tuple. "Lists" cannot be utilized as dictionary keys because they are mutable.

Next TopicPython Set




Latest Courses