Python Tuples
Tuples
A tuple is a container which holds a series of comma-separated values (items or elements) between parentheses such as an (x, y) co-ordinate. Tuples are like lists, except they are immutable (i.e. you cannot change its content once created) and can hold mix data types. Tuples play a sort of "struct" role in Python -- a convenient way to pass around a little logical, fixed size bundle of values.
Contents:
- Tuple commands
- Create a tuple
- How to get an item of the tuple in Python?
- How to know if an element exists within a tuple in Python?
- List to tuple
- Unpack a tuple in several variables
- Add item in Python tuple!
- Clone a tuple
- In Python how to know the number of times an item has repeated
- Remove an item from a tuple
- Slice a tuple
- How to get the index of an item of the tuple in Python?
- The size of a tuple
- How operators + and * are used with a Python tuple?
- Slice of a tuple using step parameter.
- Modify items of a tuple
- Python Data Types: Tuple - Exercises, Practice, Solution
Tuple: Commands
Tuple is an immutable and hashable list.
<tuple> = () <tuple> = (<el>, ) <tuple> = (<el_1>, <el_2> [, ...])
Named Tuple
Tuple's subclass with named elements.
>>> from collections import namedtuple >>> Point = namedtuple('Point', 'x y') >>> p = Point(1, y=2) Point(x=1, y=2) >>> p[0] 1 >>> p.x 1 >>> getattr(p, 'y') 2 >>> p._fields # Or: Point._fields ('x', 'y')
Create a tuple?
To create a tuple, just list the values within parenthesis separated by commas. The "empty" tuple is just an empty pair of parenthesis
How to get an item of the tuple in Python?
How to know if an element exists within a tuple in Python?
List to tuple
Unpack a tuple in several variables
Add item in Python tuple!
Clone a tuple
In Python how to know the number of times an item has repeated
Remove an item from a tuple
Slice a tuple
Find the index of an item of the tuple
The size of a tuple
How operators + and * are used with a Python tuple?
Slice of a tuple using step parameter
Modify items of a tuple
Previous: Python Dictionary
Next: Python Sets
Test your Python skills with w3resource's quiz
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics