Python access tuple element

Python Tuple

A tuple in Python is similar to a list. The difference between the two is that we cannot change the elements of a tuple once it is assigned whereas we can change the elements of a list.

Creating a Tuple

A tuple is created by placing all the items (elements) inside parentheses () , separated by commas. The parentheses are optional, however, it is a good practice to use them.

Читайте также:  Компилятор python с tkinter

A tuple can have any number of items and they may be of different types (integer, float, list, string, etc.).

# Different types of tuples # Empty tuple my_tuple = () print(my_tuple) # Tuple having integers my_tuple = (1, 2, 3) print(my_tuple) # tuple with mixed datatypes my_tuple = (1, "Hello", 3.4) print(my_tuple) # nested tuple my_tuple = ("mouse", [8, 4, 6], (1, 2, 3)) print(my_tuple)
() (1, 2, 3) (1, 'Hello', 3.4) ('mouse', [8, 4, 6], (1, 2, 3))

In the above example, we have created different types of tuples and stored different data items inside them.

As mentioned earlier, we can also create tuples without using parentheses:

my_tuple = 1, 2, 3 my_tuple = 1, "Hello", 3.4

Create a Python Tuple With one Element

In Python, creating a tuple with one element is a bit tricky. Having one element within parentheses is not enough.

We will need a trailing comma to indicate that it is a tuple,

var1 = ("Hello") # string var2 = ("Hello",) # tuple

We can use the type() function to know which class a variable or a value belongs to.

var1 = ("hello") print(type(var1)) # # Creating a tuple having one element var2 = ("hello",) print(type(var2)) # # Parentheses is optional var3 = "hello", print(type(var3)) #
  • («hello») is a string so type() returns str as class of var1 i.e.
  • («hello»,) and «hello», both are tuples so type() returns tuple as class of var1 i.e.

Access Python Tuple Elements

Like a list, each element of a tuple is represented by index numbers (0, 1, . ) where the first element is at index 0.

We use the index number to access tuple elements. For example,

1. Indexing

We can use the index operator [] to access an item in a tuple, where the index starts from 0.

So, a tuple having 6 elements will have indices from 0 to 5. Trying to access an index outside of the tuple index range( 6,7. in this example) will raise an IndexError .

The index must be an integer, so we cannot use float or other types. This will result in TypeError .

Likewise, nested tuples are accessed using nested indexing, as shown in the example below.

# accessing tuple elements using indexing letters = ("p", "r", "o", "g", "r", "a", "m", "i", "z") print(letters[0]) # prints "p" print(letters[5]) # prints "a"

2. Negative Indexing

Python allows negative indexing for its sequences.

The index of -1 refers to the last item, -2 to the second last item and so on. For example,

# accessing tuple elements using negative indexing letters = ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z') print(letters[-1]) # prints 'z' print(letters[-3]) # prints 'm'

3. Slicing

We can access a range of items in a tuple by using the slicing operator colon : .

# accessing tuple elements using slicing my_tuple = ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z') # elements 2nd to 4th index print(my_tuple[1:4]) # prints ('r', 'o', 'g') # elements beginning to 2nd print(my_tuple[:-7]) # prints ('p', 'r') # elements 8th to end print(my_tuple[7:]) # prints ('i', 'z') # elements beginning to end print(my_tuple[:]) # Prints ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')
('r', 'o', 'g') ('p', 'r') ('i', 'z') ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')
  • my_tuple[1:4] returns a tuple with elements from index 1 to index 3.
  • my_tuple[:-7] returns a tuple with elements from beginning to index 2.
  • my_tuple[7:] returns a tuple with elements from index 7 to the end.
  • my_tuple[:] returns all tuple items.

Note: When we slice lists, the start index is inclusive but the end index is exclusive.

Python Tuple Methods

In Python ,methods that add items or remove items are not available with tuple. Only the following two methods are available.

Some examples of Python tuple methods:

my_tuple = ('a', 'p', 'p', 'l', 'e',) print(my_tuple.count('p')) # prints 2 print(my_tuple.index('l')) # prints 3
  • my_tuple.count(‘p’) — counts total number of ‘p’ in my_tuple
  • my_tuple.index(‘l’) — returns the first occurrence of ‘l’ in my_tuple

Iterating through a Tuple in Python

We can use the for loop to iterate over the elements of a tuple. For example,

languages = ('Python', 'Swift', 'C++') # iterating through the tuple for language in languages: print(language)

Check if an Item Exists in the Python Tuple

We use the in keyword to check if an item exists in the tuple or not. For example,

languages = ('Python', 'Swift', 'C++') print('C' in languages) # False print('Python' in languages) # True
  • ‘C’ is not present in languages , ‘C’ in languages evaluates to False .
  • ‘Python’ is present in languages , ‘Python’ in languages evaluates to True .

Advantages of Tuple over List in Python

Since tuples are quite similar to lists, both of them are used in similar situations.

However, there are certain advantages of implementing a tuple over a list:

  • We generally use tuples for heterogeneous (different) data types and lists for homogeneous (similar) data types.
  • Since tuples are immutable, iterating through a tuple is faster than with a list. So there is a slight performance boost.
  • Tuples that contain immutable elements can be used as a key for a dictionary. With lists, this is not possible.
  • If you have data that doesn’t change, implementing it as tuple will guarantee that it remains write-protected.

Table of Contents

  • Introduction
  • Creating a Tuple
  • Create a Python Tuple With one Element
  • Access Python Tuple Elements
  • Indexing
  • Negative Indexing
  • Slicing
  • Python Tuple Methods
  • Iterating through a Tuple in Python
  • Check if an Item Exists in the Python Tuple
  • Advantages of Tuple over List in Python

Источник

Python — Access Tuple Items

You can access tuple items by referring to the index number, inside square brackets:

Example

Print the second item in the tuple:

Note: The first item has index 0.

Negative Indexing

Negative indexing means start from the end.

-1 refers to the last item, -2 refers to the second last item etc.

Example

Print the last item of the tuple:

Range of Indexes

You can specify a range of indexes by specifying where to start and where to end the range.

When specifying a range, the return value will be a new tuple with the specified items.

Example

Return the third, fourth, and fifth item:

Note: The search will start at index 2 (included) and end at index 5 (not included).

Remember that the first item has index 0.

By leaving out the start value, the range will start at the first item:

Example

This example returns the items from the beginning to, but NOT included, «kiwi»:

By leaving out the end value, the range will go on to the end of the list:

Example

This example returns the items from «cherry» and to the end:

Range of Negative Indexes

Specify negative indexes if you want to start the search from the end of the tuple:

Example

This example returns the items from index -4 (included) to index -1 (excluded)

thistuple = («apple», «banana», «cherry», «orange», «kiwi», «melon», «mango»)
print(thistuple[-4:-1])

Check if Item Exists

To determine if a specified item is present in a tuple use the in keyword:

Example

Check if «apple» is present in the tuple:

thistuple = («apple», «banana», «cherry»)
if «apple» in thistuple:
print(«Yes, ‘apple’ is in the fruits tuple»)

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

Binary Study

Python provides us various mechanism to select a single or a range of elements. We can use indexing, reverse indexing and slicing to access elements from a tuple in Python. Let’s discuss the these three ways in detail:

1. Accessing Tuple Elements Using Indexing

Simplest is direct access where we use index operator [ ] to pick an item from tuple; the index is always an integer.

>>>print(«The tuple:», my_tuple, «Length:», len(my_tuple))

The tuple: (‘a’, ‘e’, ‘i’, ‘o’, ‘u’) Length: 5

Indexing the first element

Indexing the last element

>>>print(«my_tuple[length-1]:», my_tuple[len(my_tuple) — 1])

Accessing a non-existent member will raise Error

print(«my_tuple[length+1] Error:», ex)

my_tuple[length+1] Error: tuple index out of range

Indexing a non-integer index will raise TypeErr

my_tuple[0.0] Error: tuple indices must be integers or slices, not float

Indexing in a tuple of tuples

>>>t_o_t = ((‘jan’, ‘feb’, ‘mar’), (‘sun’, ‘mon’, ‘wed’))

Accessing elements from the first sub tuple

Accessing elements from the second sub tuple

2. Accessing Tuple Elements Using Reverse Indexing

Python tuple supports reverse indexing, i.e., accessing elements using (-ve) index values.

Index -1 represents last item.

An index -2 will refer to the second item from the end.

IndexError: tuple index out of range

3. Accessing Tuple Elements Using Slicing Operator

>>> days = (‘mon’, ‘tue’, ‘wed’ ,’thu’, ‘fri’, ‘sat’, ‘sun’)

Accessing elements leaving the first one

Accessing elements between first & fifth positions excluding ones at ist & fifth position

Accessing elements after the fifth position

accessing the first five elements

Accessing elements that appears after # counting five from rear end

Accessing five elements from the rear

Accessing elements from the start to end (every element)

(‘mon’, ‘tue’, ‘wed’, ‘thu’, ‘fri’, ‘sat’, ‘sun’)

Источник

Оцените статью