Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Basic Tuples Operations in Python
Tuples respond to the + and * operators much like strings; they mean concatenation and repetition here too, except that the result is a new tuple, not a string.
In fact, tuples respond to all of the general sequence operations we used on strings in the prior chapter −
Basic Tuple Operations
| Python Expression | Results | Description |
|---|---|---|
len((1, 2, 3)) |
3 | Length |
(1, 2, 3) + (4, 5, 6) |
(1, 2, 3, 4, 5, 6) | Concatenation |
('Hi!',) * 4 |
('Hi!', 'Hi!', 'Hi!', 'Hi!') | Repetition |
3 in (1, 2, 3) |
True | Membership |
for x in (1, 2, 3): print(x) |
1 2 3 | Iteration |
Examples
Length Operation
The len() function returns the number of elements in a tuple ?
numbers = (1, 2, 3, 4, 5) print(len(numbers))
5
Concatenation Operation
The + operator combines two tuples to create a new tuple ?
tuple1 = (1, 2, 3) tuple2 = (4, 5, 6) result = tuple1 + tuple2 print(result)
(1, 2, 3, 4, 5, 6)
Repetition Operation
The * operator repeats a tuple a specified number of times ?
greeting = ('Hello',)
repeated = greeting * 3
print(repeated)
('Hello', 'Hello', 'Hello')
Membership Operation
The in operator checks if an element exists in a tuple ?
colors = ('red', 'green', 'blue')
print('red' in colors)
print('yellow' in colors)
True False
Iteration Operation
You can iterate through tuple elements using a for loop ?
fruits = ('apple', 'banana', 'orange')
for fruit in fruits:
print(fruit)
apple banana orange
Conclusion
Tuples support all common sequence operations like concatenation, repetition, membership testing, and iteration. These operations create new tuples without modifying the original ones, maintaining tuple immutability.
