eolas/Programming_Languages/Python/Syntax/Tuples_in_Python.md

107 lines
1.4 KiB
Markdown
Raw Normal View History

2023-02-14 09:16:11 +00:00
---
categories:
- Programming Languages
tags: [python, data-structures]
---
# Tuples in Python
Tuples are one of the main data-structures or containers in Python.
Tuples have the following properties:
- They are **ordered**
- They have a **fixed size**
- They are **immutable** and cannot be modified
- **Allow duplicate** members
- They are **indexed**
2023-02-15 07:36:48 +00:00
As with all containers in Python they permit any data type.
> Tuples are denoted with `(...)`
## Basic usage
2023-02-14 09:16:11 +00:00
```python
tup1 = (1, 3, 5, 7)
2023-02-15 07:36:48 +00:00
print(tup1[0])
print(tup1[1])
print(tup1[2])
print(tup1[3])
2023-02-14 09:16:11 +00:00
"""
2023-02-15 07:36:48 +00:00
1
3
5
7
2023-02-14 09:16:11 +00:00
"""
2023-02-15 07:36:48 +00:00
```
2023-02-14 09:16:11 +00:00
2023-02-15 07:36:48 +00:00
## Slicing
```python
tup1 = (1, 3, 5, 7)
2023-02-14 09:16:11 +00:00
2023-02-15 07:36:48 +00:00
print(tup1[1:3])
print(tup1[:3])
print(tup1[1:])
print(tup1[::-1])
2023-02-14 09:16:11 +00:00
"""
2023-02-15 07:36:48 +00:00
(3, 5)
(1, 3, 5)
(3, 5, 7)
(7, 5, 3, 1)
2023-02-14 09:16:11 +00:00
"""
2023-02-15 07:36:48 +00:00
```
2023-02-14 09:16:11 +00:00
2023-02-15 07:36:48 +00:00
## Looping
2023-02-14 09:16:11 +00:00
2023-02-15 07:36:48 +00:00
```python
2023-02-14 09:16:11 +00:00
tup3 = ('apple', 'pear', 'orange', 'plum', 'apple')
for x in tup3:
print(x)
2023-02-14 15:37:40 +00:00
"""
apple
pear
orange
plum
apple
"""
2023-02-15 07:36:48 +00:00
```
2023-02-14 15:37:40 +00:00
2023-02-15 07:36:48 +00:00
## Useful methods and predicates
```python
tup3 = ('apple', 'pear', 'orange', 'plum', 'apple')
2023-02-14 09:16:11 +00:00
2023-02-15 07:36:48 +00:00
# Count instances of a member
print(tup3.count('apple'))
2023-02-14 15:37:40 +00:00
# 2
2023-02-15 07:36:48 +00:00
# Get index of a member
print(tup3.index('pear'))
# 1
2023-02-14 15:37:40 +00:00
2023-02-15 07:36:48 +00:00
# Check for membership
2023-02-14 09:16:11 +00:00
if 'orange' in tup3:
print('orange is in the Tuple')
2023-02-14 15:37:40 +00:00
# orange is in the Tuple
2023-02-15 07:36:48 +00:00
```
## Nest tuples
```python
2023-02-14 15:37:40 +00:00
2023-02-14 09:16:11 +00:00
tuple2 = ('John', 'Denise', 'Phoebe', 'Adam')
tuple3 = (42, tuple1, tuple2, 5.5)
print(tuple3)
2023-02-14 15:37:40 +00:00
# (42, (1, 3, 5, 7), ('John', 'Denise', 'Phoebe', 'Adam'), 5.5)
2023-02-14 09:16:11 +00:00
```
2023-02-15 07:36:48 +00:00
// TODO: How to flatten a tuple?