Skip to content

Latest commit

 

History

History
463 lines (334 loc) · 11.5 KB

07.Tuple.md

File metadata and controls

463 lines (334 loc) · 11.5 KB

Lesson 7: Data Structures p.2 (tuple)

Tuples are the static snapshots of data, providing a reliable and immutable record of information in code."

Content

  1. Overview of Tuples
  2. Features Overview
  3. Iterations
  4. Quiz
  5. Homework

1. Overview of Tuples

In Python a tuple - is an immutable, ordered sequence of items.

Similar to lists, tuples can contain elements of different data types, but cannot be modified after their creation.

Why do we need them, if we have lists?

Advantage Description
Memory Efficiency Have a fixed size, which makes them more memory-efficient than lists.
Faster than Lists Due to their immutability, tuples can be slightly faster than lists when iterating through large datasets.
Fixed Data Ideal for storing data that shouldn't change over time, such as configuration values or constants.
Easier Debugging With immutability, it's much easier to track changes and debug your code, as tuples don't change state unexpectedly.

There are more advantages which we will see during expanding of our knowledge into the next lessons:

Advantage Description
Suitable as Dictionary Keys Tuples can be used as keys in dictionaries due to their immutability.
Functionality in Functions Useful for passing multiple values to and from functions, ensuring they remain unaltered.
Hashable Tuples are hashable, which means they can be used as keys in sets or as unique identifiers.

1.1 Syntax and Creation

In order to create an empty tuple we can use the following syntax:

Example

tuple_1 = ()
tuple_2 = tuple()

print(tuple_1, tuple_2)
print(type(tuple_1), type(tuple_2))

Output

() ()
<class 'tuple'> <class 'tuple'>

1.2 Convert iterables into tuple

As with lists you can convert other iterable data types to a tuple using the tuple() constructor.

This feature is particularly useful when you need the immutability of tuples, or when a specific API requires a tuple instead of another iterable, or you want to have a representation of some data in this format.

Example

# Converting a list to a tuple
my_list = [1, 2, 3]
my_tuple = tuple(my_list)
print(my_tuple)

# Converting a string to a tuple
my_string = "hello"
string_tuple = tuple(my_string)
print(string_tuple)

Output

(1, 2, 3)
('h', 'e', 'l', 'l', 'o')

You can create a tuple just asigning a few variables into with coma and parentheses.

Example

another_tuple = 2, 'world', 1.618
print("Another tuple:", another_tuple)
print("Type:", type(another_tuple))

Output

Another tuple: (2, 'world', 1.618)
Type: <class 'tuple'>

1.3 Immutability

Once a tuple is created, its elements cannot be changed, removed, or added. This immutability makes tuples a reliable data structure for storing unchangeable data.

IMPORTANT: Though, you have to understand that if the tuple has mutable objects inside, you can access and modify them there.

Example

tuple_1 = ([1,2,3], [5,6])
print("Tuple before:", tuple_1)
print("ID before:", id(tuple_1))

# Modifying a mutable object inside the tuple
tuple_1[-1].append(4)

print("Tuple after:", tuple_1)
print("ID after:", id(tuple_1))

Output

Tuple before: ([1, 2, 3], [5, 6])
ID before: 139653455025920
Tuple after: ([1, 2, 3], [5, 6, 4])
ID after: 139653455025920

Yes, it's Python baby, but I promise, you will get used to this once understand the concept of objects and how do they work.

Note that id of the tuple hasn't changed, but id of the objects inside has.

2. Features Overview

Same as lists Python supports indexing, slicing, concatenation, multiplication, unpacking and some built-in functions.

Suppose we have the following two tuples:

first_tuple = (1, 'hello', 3.14)
second_tuple = 2, 'world', 1.618

2.1 Indexing and Slicing in Tuples

Example

# Indexing
print(first_tuple[1])

# Slicing
print(second_tuple[1:])

Output

hello
('world', 1.618)

2.2 Concatenation and Multiplication

Example

# Concatenation
combined_tuple = first_tuple + second_tuple

# Multiplication
repeated_tuple = first_tuple * 2

print("Combined:", combined_tuple)
print("Repeated:", repeated_tuple)

Output

Combined: (1, 'hello', 3.14, 2, 'world', 1.618)
Repeated: (1, 'hello', 3.14, 1, 'hello', 3.14)

2.3 Unpacking

Example

x, y, z = first_tuple
print(f"x={x},y={y},z={z}")

Output

x=1,y=hello,z=3.14

2.4 Operator in

Example

if 'hello' in first_tuple:
    print("Found 'hello' in the tuple!")   

Output

Found 'hello' in the tuple!

2.5 Functions

Example

constants = (3.14, 2.7, 36.6)

length = len(constants)
max_value = max(constants)
min_value = min(constants)
sum_value = sum(constants)
sorted_list = sorted(constants)

print("Lenght:", length)
print("Max:", max_value)
print("Min:", min_value)
print("Sum:", sum_value)
print("Sorted:", sorted_list)      # Note that ``sorted()`` returns a ``list`` instead!

Output

Lenght: 3
Max: 36.6
Min: 2.7
Sum: 42.44
Sorted: [2.7, 3.14, 36.6]

Basically, it's very similar to lists, but don't forget that Python doesn't allow modification of immutable objects.

2.6 Tuple Methods

There are only two methods for tuples.

nums = (1, 2, 3)
Method Description Example Output
index(x) Returns the index of the first item whose value is x. nums.index(3) 2
count(iterable) Returns the number of times x appears in the tuple. nums.count(1) 1

3. Iterations

Typically we use tuples for stroing the constants.

3.1 Using for in

Example

# Rainbow is a constant so that ``tuple`` is a great choice to store its colors
rainbow = ('red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet')
for color in rainbow:
    print(color)

Output

red
orange
yellow
green
blue
indigo
violet

3.2 for index in range(len(tuple))

# Tuple of prime numbers
primes = (2, 3, 5, 7, 11)
for index in range(len(primes)):
    print(f"Prime number at index {index} is {primes[index]}")

Output

Prime number at index 0 is 2
Prime number at index 1 is 3
Prime number at index 2 is 5
Prime number at index 3 is 7
Prime number at index 4 is 11

3.3 Using enumerate()

There is a built-in function called enumerate(), that adds a counter to an iterable.

It can be used with any iterable. and be particulary useful with when both the element and its index are needed.

# Tuple of weekdays
weekdays = ('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday')
for index, day in enumerate(weekdays):
    print(f"{day} is the {index+1}-th day of the workweek.")
Monday is the 1-th day of the workweek.
Tuesday is the 2-th day of the workweek.
Wednesday is the 3-th day of the workweek.
Thursday is the 4-th day of the workweek.
Friday is the 5-th day of the workweek.

4. Quiz

Question 1:

What will be the output of the following code?

my_tuple = (10, 20, 30, 40, 50)
print(my_tuple[-2])

Question 2:

What happens when you try to modify an element in a tuple?

my_tuple = (1, 2, 3, 4, 5)
my_tuple[0] = 6

Question 3:

Which of the following is the correct way to create a tuple?

A) my_tuple = tuple(1, 2, 3)
B) my_tuple = 1, 2, 3
C) my_tuple = (1,)
D) my_tuple = [1, 2, 3]


Question 4:

What does the count() method do in a tuple?

A) Counts the number of occurrences of an element in the tuple.
B) Counts the total number of elements in the tuple.
C) Returns the first occurrence of an element in the tuple.
D) None of the above.


Question 5:

What is the output of the following tuple slicing?

my_tuple = (0, 1, 2, 3, 4, 5)
print(my_tuple[1:4])

A) (1, 2)
B) (1, 2, 3)
C) (2, 3, 4)
D) (0, 1, 2)


Question 6:

How does enumerate() enhance the iteration process in tuples?

A) It sorts the tuple before iteration.
B) It adds a counter as part of the tuple element during iteration.
C) It reverses the tuple during iteration.
D) It performs unpacking of the tuple elements.


Question 7:

Which of the following is true about tuple concatenation?

A) It modifies the original tuple.
B) It creates a new tuple.
C) It's not possible to concatenate tuples.
D) It removes duplicates while concatenating.


Question 8:

Which of the following statements about tuples is NOT true?

A) Tuples are immutable.
B) Tuples can contain elements of different data types.
C) Tuples do not support slicing.
D) Tuples can be used as keys in dictionaries.

5. Homework

Task 1: Tuple Analyzer

Objective: Write a program that allows the user to input a sequence of numbers, store them in a tuple, and analyze the tuple to provide insights.

Input: Enter numbers separated by commas: 1, 2, 3, 4, 5
Output: Tuple: (1, 2, 3, 4, 5)
        Sum: 15
        Average: 3
        Maximum: 5
        Minimum: 1

Task 2: Tuple Sorter

Objective: Develop a program to sort elements of multiple tuples based on user preference (ascending or descending order).

Input: Enter elements of the tuple: 5, 1, 9, 3
       Sort order (asc/desc): asc
Output: Sorted Tuple: (1, 3, 5, 9)

Task 3: Tuple Element Finder

Objective: Create a program that finds specific elements within a tuple based on user queries.

Input: Tuple: (1, 2, 3, 4, 5, 6)
       Enter element to search: 4
Output: Element 4 found at index: 3

Task 4: Enumerate Sports Teams

Objective: Use the enumerate() function to list sports teams and their ranking based on user input.

Input: Enter teams (separated by commas): Lakers, Bulls, Celtics
Output: Team Rankings:
       1. Lakers
       2. Bulls
       3. Celtics

Task 5: Mini Code Review

Objective: Try rewriting some programs from the previous homework where it's applicable and where tuples are a better choice.