Python for Project Managers 9 – Tuples


Photo by Linda Eller-Shein on Pexels.com

1. What is a Tuple?

A tuple in Python is an ordered and immutable data structure used to store multiple values in a single variable. It is very similar to a list, but the main difference is that tuples cannot be changed after creation.

my_tuple = (1, 2, 3)

2. Creating a Tuple

  • Using parentheses:
fruits = ("apple", "banana", "cherry")
  • Parentheses are optional (a comma is enough):
colors = "red", "green", "blue"
  • For a single-element tuple, a trailing comma is required:
one_element = ("hello",)

3. Accessing Tuple Elements

You can access tuple elements using index numbers. Indexing starts at 0.

print(fruits[0])  # apple
print(fruits[-1]) # cherry

4. Iterating Through a Tuple

for fruit in fruits:
    print(fruit)

5. Nested Tuples

Tuples can contain other tuples:

nested = (1, 2, (3, 4))
print(nested[2])      # (3, 4)
print(nested[2][0])   # 3

6. Immutability

Tuple contents cannot be changed after creation. The following will raise an error:

fruits[1] = "orange"  # ❌ TypeError

7. Advantages of Tuples

  • Faster: Tuples consume less memory and are faster than lists.
  • Safer: Immutable nature ensures data integrity.
  • Hashable: Tuples can be used as keys in dictionaries (lists cannot).

8. Tuple Functions

FunctionDescription
len(t)Returns the number of elements
t.count(x)Counts how many times x appears
t.index(x)Returns the index of the first occurrence of x
numbers = (4, 2, 7, 2, 9)
print(numbers.count(2))  # 2
print(numbers.index(7))  # 2

9. Converting Between Tuples and Lists

my_list = [1, 2, 3]
my_tuple = tuple(my_list)

new_list = list(my_tuple)

Summary:

FeatureTupleList
Ordered
Mutable❌ (immutable)✅ (mutable)
Syntax()[]
PerformanceFasterMore flexible
Use CasesFixed sets, safe dataDynamic collections

Try Yourself: https://colab.research.google.com/drive/1w3s04eF5v9Y3OiXZgdA4k8s47SscLaEY?usp=sharing

Bir Cevap Yazın

This site uses Akismet to reduce spam. Learn how your comment data is processed.