PYTHON TUPLE

By YBI Foundation

CONTENT

1. Introduction

2. Creating Tuple

3. Tuple Methods

4. Tuple Functions

​Introduction

Tuples are simple yet powerful data structures in Python, and their immutability makes them ideal for specific use cases where data integrity and performance are important.

​Creating Tuple

Creating lists in Python is a straightforward process. The most common way is to enclose a comma-separated sequence of items within square brackets [ ]. This allows you to directly initialize a list with specific values, whether they are numbers, strings, or a mix of data types. 

For instance, my_list = [1, "hello", 3.14] creates a list containing an integer, a string, and a float. 

Alternatively, you can create an empty list using my_list = [ ] and then add elements later using methods like append() or insert(). 

Another powerful technique is to use the list() constructor, which can convert other iterable data types, such as tuples or strings, into lists. 

TUPLE INDEXING

​Tuple Indexing

Indexing in Python refers to the process of accessing individual elements within a list by their position. Here's a breakdown of the key concepts:
Zero-Based Indexing:
Python lists use zero-based indexing, meaning the first element in a list has an index of 0, the second element has an index of 1, and so on.
Accessing Elements:
You access list elements using square brackets [] and the index number. For example, my_list[0] retrieves the first element of the list my_list.
Negative Indexing:
Python also supports negative indexing, which allows you to access elements from the end of the list.
my_list[-1] retrieves the last element, my_list[-2] retrieves the second-to-last element, and so on.
Slicing:
In addition to accessing individual elements, you can also extract a portion of a list using slicing.
Slicing uses the syntax my_tuple[start:stop:step], where:
start is the index of the first element to include (inclusive).
stop is the index of the first element to exclude (exclusive).
step is the increment between elements.
IndexError:
If you try to access an index that is outside the range of valid indices for a list, Python will raise an IndexError.
TUPLE METHODS

​Tuple Methods

In Python, tuples are immutable sequences, meaning once they are created, their contents cannot be changed. Because of this immutability, tuples have fewer built-in methods compared to mutable data types like lists.

If you need to modify a tuple, you can convert it to a list, make changes, and then convert it back to a tuple.

1. count(item): Returns the number of times a specified value appears in the tuple.

Syntax: tuple.count(value)

value: The value to search for.

​Code </>:
​# count number of occurrence of 2​
my_tuple = (1, 2, 3, 2, 4, 2)
print(my_tuple.count(2))

Output:

3

2. index(value, start, end): Returns the index of the first occurrence of a specified value in the tuple.

​Syntax: tuple.index(value, start, end)
value: The value to search for.
start (optional): The index to start the search from.
end (optional): The index to end the search at.

​Code </>:
​# search index of first occurrence of element 2 from beginning
my_tuple = (1, 2, 3, 2, 4, 2)
print(my_tuple.index(2))

Output:

1

​Code </>:
​# search index of first occurrence of element 2 after index 2 but before 5 (excluding)
my_tuple = (1, 2, 3, 2, 4, 2)
print(my_tuple.index(2, 2, 5))

Output:

3

TUPLE FUNCTIONS

Tuple Functions

These are built-in Python functions that can operate on lists (among other iterables). They are general-purpose functions, not tied specifically to list objects.
1. len(tuple): Returns the number of items in the tuple.

Code </>:

returns the length of my_list

len(my_list)

Output:


2. min(tuple): Returns the smallest item in the tuple.

Code </>:

returns the smallest element in my_list

min(my_list)

Output:


3. max(tuple): Returns the largest item in the tuple.

Code </>:

returns the largest element in my_list

max(my_list)

Output:


4. sum(tuple): Returns the sum of all items in the tuple (only for numeric tuple).

Code </>:

returns the sum of all elements in my_list

sum(my_list)

Output:


5. sorted(tuple, key=None, reverse= False): Returns a new sorted tuple from the elements of the tuple. The original tuple remains unchanged.

Code </>:

 returns a new list sorted in descending order

sorted(my_list, reverse=True)

Output:


6. any(tuple): Returns True if at least one element in the tuple is True (or truthy).

Code </>:

 returns True if any element in my_list is True

any(my_list)

Output:


7. all(tuple): Returns True if all elements in the list are True (or truthy).

Code </>:

 returns True if all elements in my_list are True

all(my_list)

Output:


8. list(iterable): Converts an iterable (e.g., tuple, string, set) into a list.

Code </>:

 converts the string 'hello' into ['h', 'e', 'l', 'l', 'o']

list('hello')

Output:


Examples

Examples

# Example list
my_list = [3, 1, 4, 1, 5, 9]
# Append
my_list.append(2)  # [3, 1, 4, 1, 5, 9, 2]
# Extend
my_list.extend([6, 5])  # [3, 1, 4, 1, 5, 9, 2, 6, 5]
# Insert
my_list.insert(2, 'x')  # [3, 1, 'x', 4, 1, 5, 9, 2, 6, 5]
# Remove
my_list.remove('x')  # [3, 1, 4, 1, 5, 9, 2, 6, 5]
# Pop
popped_item = my_list.pop(1)  # popped_item = 1, my_list = [3, 4, 1, 5, 9, 2, 6, 5]
# Clear
my_list.clear()  # []
# Index
my_list = [3, 1, 4, 1, 5, 9]
index = my_list.index(1)  # index = 1
# Count
count = my_list.count(1)  # count = 2
# Sort
my_list.sort()  # [1, 1, 3, 4, 5, 9]
# Reverse
my_list.reverse()  # [9, 5, 4, 3, 1, 1]
# Copy
new_list = my_list.copy()  # new_list = [9, 5, 4, 3, 1, 1]
# Len
length = len(my_list)  # length = 6
# Min
minimum = min(my_list)  # minimum = 1
# Max
maximum = max(my_list)  # maximum = 9
# Sum
total = sum(my_list)  # total = 23
# Sorted
sorted_list = sorted(my_list, reverse="True)"  # sorted_list = [9, 5, 4, 3, 1, 1]
# Any
any_true = any(my_list)  # any_true = True
# All
all_true = all(my_list)  # all_true = True
# List
converted_list = list('hello')  # converted_list = ['h', 'e', 'l', 'l', 'o']

Key Differences Between Tuples and Lists

1. Mutability
  1. Tuples are immutable, meaning you cannot modify their contents after creation.
  2. Lists are mutable, so you can add, remove, or change elements.
Performance

Tuples are generally faster than lists because of their immutability.

Use Cases
  1. Use tuples for fixed collections of items (e.g., coordinates, database records).
  2. Use lists for dynamic collections that may change over time.
  3. When you want to ensure the data cannot be modified (e.g., constants, keys in dictionaries).
  4. When performance is critical, and you don't need to modify the data.
  5.  When working with heterogeneous data (e.g., storing different types of data together).