Python Tuples: Class Notes
Python Tuples: In-Depth Class Notes
1. Introduction to Tuples
- Definition:
A tuple is an ordered, immutable collection of items. Think of it as a container that holds a fixed set of values which cannot be changed once defined. - Key Characteristics:
- Immutable: Once created, you cannot alter its elements.
- Ordered: Elements have a defined order, which means you can access them via an index.
- Heterogeneous: Tuples can store items of different data types (e.g., integers, strings, etc.).
- Creating a Tuple:
Use parentheses()
to define a tuple.my_tuple = (10, 20, 30) single_element = (5,) # Note the comma for a single-element tuple.
2. Indexing and Membership
- Indexing:
Access individual elements using an index (starting from 0).print(my_tuple[0]) # Outputs: 10 print(my_tuple[-1]) # Outputs: 30 (using negative indexing)
- Membership:
Check if an element exists in a tuple using thein
keyword.if 20 in my_tuple: print("20 is present in the tuple")
- Slicing:
Extract a part of the tuple using slice notation[start:end]
.sub_tuple = my_tuple[1:3] # Outputs: (20, 30)
3. Tuple Operations
A. Concatenation
- Joining Tuples:
Use the+
operator to combine two tuples.t1 = (1, 2) t2 = (3, 4) combined = t1 + t2 # (1, 2, 3, 4)
B. Repetition
- Repeating Tuples:
Use the*
operator to repeat a tuple several times.repeated = t1 * 3 # (1, 2, 1, 2, 1, 2)
C. Membership (Review)
- Already Covered:
Thein
keyword checks for membership within a tuple.
D. Slicing (Review)
- Extracting Sub-tuples:
Slice notation helps in retrieving parts of a tuple as shown above.
4. Built-in Functions and Methods
Python provides several useful functions and methods to work with tuples:
len()
Returns the number of elements in the tuple.print(len(my_tuple)) # 3
tuple()
Converts an iterable (like a list) into a tuple.list_example = [1, 2, 3] converted = tuple(list_example) # (1, 2, 3)
count()
Returns the number of times a specified value appears in the tuple.t = (1, 2, 2, 3) print(t.count(2)) # 2
index()
Returns the index of the first occurrence of a specified value.print(t.index(3)) # 3
sorted()
Returns a new sorted list from the elements of the tuple.unsorted = (3, 1, 2) print(sorted(unsorted)) # [1, 2, 3]
min()
andmax()
Return the smallest and largest elements in the tuple (if elements are comparable).print(min(my_tuple)) # 10 print(max(my_tuple)) # 30
sum()
Returns the sum of all elements in the tuple (all elements must be numbers).print(sum(my_tuple)) # 10 + 20 + 30 = 60
5. Tuple Assignment and Nested Tuples
- Tuple Assignment:
You can assign tuple elements to individual variables in one line.a, b, c = my_tuple # a=10, b=20, c=30
- Nested Tuples:
Tuples can contain other tuples (or other data structures), allowing you to create complex structures.nested = ((1, 2), (3, 4), (5, 6)) print(nested[1]) # (3, 4)
6. Tuples vs. Lists
- Tuples:
- Immutable: Cannot be changed after creation.
- Often used for fixed collections of items where data integrity is important.
- Lists:
- Mutable: Can be modified (items can be added, removed, or changed).
- Suitable when you need a dynamic collection of items.
7. Tuple Unpacking
Important Note:
The number of variables must match the number of elements in the tuple.
What Is It?
Tuple unpacking allows you to assign each element of a tuple to a variable. a, b, c = my_tuple # a = 1, b = 2, c = 3
8. Suggested Programs and Examples
A. Finding Minimum, Maximum, and Mean
# Sample tuple of numbers
numbers = (10, 20, 30, 40, 50)
# Finding minimum, maximum, and mean
minimum = min(numbers)
maximum = max(numbers)
mean = sum(numbers) / len(numbers)
print("Minimum:", minimum)
print("Maximum:", maximum)
print("Mean:", mean)
B. Linear Search on a Tuple of Numbers
def linear_search(tup, target):
for index, value in enumerate(tup):
if value == target:
return index # Return the index of the target
return -1 # Target not found
# Example usage:
numbers = (10, 20, 30, 40, 50)
target = 30
result = linear_search(numbers, target)
if result != -1:
print(f"Found {target} at index {result}")
else:
print(f"{target} not found in the tuple")
C. Counting the Frequency of Elements in a Tuple
def frequency_counter(tup):
freq_dict = {}
for item in tup:
freq_dict[item] = freq_dict.get(item, 0) + 1
return freq_dict
# Example usage:
elements = (1, 2, 2, 3, 3, 3, 4)
frequency = frequency_counter(elements)
print("Frequency of elements:", frequency)
Recap
- Tuples are immutable, ordered collections.
- Indexing and slicing allow access to tuple elements.
- Operations:
- Concatenation:
+
- Repetition:
*
- Membership: using
in
- Concatenation:
- Built-in Functions/Methods:
len()
,tuple()
,count()
,index()
,sorted()
,min()
,max()
,sum()
- Tuple Assignment:
Easy assignment to variables. - Nested Tuples:
Tuples can contain other tuples. - Practical Programs:
Examples include finding min, max, mean; performing a linear search; and counting frequencies.
Feel free to ask questions if anything is unclear.