Tuples and Sets
Tuples in Python are immutable sequences used to store collections of items.
Key Characteristics
- Immutable: Once a tuple is created, its elements cannot be changed, added, or removed.
- Ordered: Elements are stored in a specific order, and you can access them by index.
- Heterogeneous: Tuples can store elements of different data types (e.g., integers, strings, lists).
Creating Tuples in Python
A tuple in Python is a finite ordered list of values that can be of different types. Tuples are used to group related data together without needing to create a custom data structure.
Syntax for Creating Tuples
A tuple is defined by placing a comma-separated list of values inside parentheses. Each value within a tuple is referred to as an item.
Example:
Tuple Creation Without Parentheses
You can also create a tuple without using parentheses, relying on commas to separate the items. However, parentheses are commonly used to enhance readability.
Creating Empty Tuples
An empty tuple can be created by simply using an empty pair of parentheses.
Nested Tuples
Tuples can store other tuples as items, allowing for the creation of complex, nested data structures. Tuples can hold different types of items, making them versatile.
Special Cases: Single and Empty Tuples
Creating a tuple with a single item requires a trailing comma to differentiate it from a regular value in parentheses.
Basic Tuple Operations in Python
Tuples in Python support various operations similar to lists. Below are some of the key operations you can perform on tuples:
-
Concatenation (
+
Operator) - You can concatenate two or more tuples using the+
operator. This operation creates a new tuple by combining the items from the given tuples.Example:
-
Repetition (
*
Operator) - The*
operator allows you to repeat the items of a tuple a specified number of times, resulting in a new tuple.Example:
-
Comparison (
==
,!=
,<
,>
,<=
,>=
Operators) - Tuples can be compared using comparison operators. The comparison is done element by element, starting from the first element.Example:
-
Membership Testing (
in
,not in
Operators) - You can check whether an item exists in a tuple using thein
ornot in
operators. The result is a Boolean value:True
if the item is present, otherwiseFalse
.Example:
-
The
tuple()
Function - Thetuple()
function is a built-in function that can be used to create a tuple from a sequence, such as a string, list, or another tuple. If no argument is provided, it creates an empty tuple.Examples:
-
Converting a String to a Tuple
-
Converting a List to a Tuple
-
Nesting Tuples
You can create a tuple of tuples, allowing for complex nested structures.
Note: When concatenating tuples, the types must be compatible. For example, you cannot directly concatenate a tuple with a string or list; you must first convert them to a tuple using the
tuple()
function.Examples of Incorrect Concatenation
-
Concatenating Tuple and String
-
Concatenating Tuple and List
-
-
Indexing and Slicing in Tuples
Tuples in Python allow you to access individual elements and extract parts of the tuple using indexing and slicing techniques. These operations are crucial for working with tuple data efficiently.
Indexing in Tuples
Indexing is used to access individual elements in a tuple. Each element in a tuple is associated with an index number, starting from 0 for the first item. You can also use negative indexing to access elements from the end of the tuple, with -1
being the last item.
Syntax:
-
Positive Indexing: The index starts at 0 for the first element, 1 for the second, and so on.
Example:
-
Negative Indexing: Negative indexes start at
-1
for the last element,-2
for the second last, and so on.Example:
Note: Accessing an index that is out of range will raise an IndexError
.
Example of an Out-of-Range Index:
Slicing in Tuples
Slicing allows you to extract a part of the tuple by specifying a range of index values. The syntax for slicing is:
Syntax:
-
start
: The index to begin slicing (inclusive). -
stop
: The index to end slicing (exclusive). -
step
: The interval between each index (optional). -
Basic Slicing: You can slice a tuple from one index to another.
Example:
-
Omitting Start or Stop: You can omit the
start
orstop
index to slice from the beginning or up to the end of the tuple, respectively.Examples:
-
Slicing with Step: The
step
parameter in slicing allows you to specify the interval between elements in the slice. By default, the step is1
, meaning every element in the specified range is included. You can change the step to select elements at different intervals.Example:
-
In the first
print(colors[::2])
, thestep
is2
, so the slice starts from the first element ('v'
) and includes every second element, resulting in('v', 'b', 'y', 'r')
. -
In the second
print(colors[1:5:2])
, the slice starts at index1
('i'
) and ends at index5
(not including index5
). Thestep
is2
, so it selects every second element within the specified range. The elements at index1
('i'
) and index3
('g'
) are included, resulting in('i', 'g')
.
-
-
Reversing a Tuple: You can reverse the elements in a tuple by using a negative
step
value.Example:
-
Negative Indexing in Slicing: You can also use negative indexing in slicing to work from the end of the tuple.
Example:
Built-In Functions Used on Tuples
Python provides several built-in functions that can be used to perform operations on tuples. These functions make it easier to work with tuple data by offering utilities like counting elements, summing numerical values, and sorting.
Common Built-In Functions for Tuples
Built-In Function | Description |
---|---|
len() | Returns the number of items in a tuple. |
sum() | Returns the sum of numbers in the tuple. |
sorted() | Returns a sorted copy of the tuple as a list, without modifying the original tuple. |
Examples:
-
Using
len()
to Count Items in a TupleThe
len()
function returns the number of elements in a tuple.- Explanation: The
len()
function is used here to determine that the tupleyears
contains 4 items.
- Explanation: The
-
Using
sum()
to Add Up Numbers in a TupleThe
sum()
function calculates the total sum of all numerical elements in a tuple.- Explanation: The
sum()
function adds up all the years in the tuple, giving a total of 7949.
- Explanation: The
-
Using
sorted()
to Sort Tuple ElementsThe
sorted()
function returns a sorted list of the tuple's elements, leaving the original tuple unchanged.-
Explanation: The
sorted()
function generates a new sorted list[1981, 1985, 1987, 1996]
from the tupleyears
. The original tuple remains unaltered. -
When using
sorted()
on tuples containing strings, the sorting is based on the ASCII values of the characters.Example:
-
Relation Between Tuples and Lists
Tuples and lists in Python are both sequence types that store collections of items. Despite their similarities, they serve different purposes and have distinct characteristics that make them suitable for different scenarios.
Key Difference
- Tuples are immutable, meaning that once a tuple is created, its elements cannot be changed, added, or removed. This immutability makes tuples a good choice for fixed collections of items where data integrity is crucial.
- Lists are mutable, allowing for modifications after creation. Items in a list can be added, removed, or changed, making lists more flexible for dynamic collections of items.
Examples:
-
Immutability of Tuples:
Attempting to modify an element of a tuple results in an error:
- Explanation: Since tuples are immutable, trying to assign a new value to an element in the
coral_reef
tuple results in aTypeError
.
- Explanation: Since tuples are immutable, trying to assign a new value to an element in the
-
Converting a Tuple to a List:
You can convert a tuple to a list to make it mutable:
- Explanation: The tuple
coral_reef
is converted into a list using thelist()
function, allowing modifications to the new list.
- Explanation: The tuple
-
Mutability of Elements Within a Tuple:
If a tuple contains a mutable item, such as a list, changes to that item are reflected in the tuple:
- Explanation: While the
european_cars
tuple itself remains immutable, the list within it (german_cars
) can be modified. The change is reflected in both the original list and the tuple because they reference the same list object.
- Explanation: While the
Relation Between Tuples and Dictionaries
Tuples and dictionaries are both versatile data structures in Python, but they serve different purposes and have unique characteristics. Tuples can be used effectively in conjunction with dictionaries in a few specific ways:
Tuples as Dictionary Keys and Values:
-
Using Tuples to Build Dictionaries:
Tuples can be utilized to create dictionaries, where each tuple represents a key-value pair. To achieve this, each tuple must contain exactly two elements: the first element is used as the key and the second as the value.
Example:
- Explanation: In this example,
fish_weight_kg
is a tuple of tuples. Each inner tuple has two elements where the first is the key and the second is the value. Thedict()
function converts this tuple of tuples into a dictionary.
- Explanation: In this example,
-
Converting Dictionaries to Tuples:
The
items()
method of a dictionary returns a view object that displays a list of tuples. Each tuple contains a key-value pair from the dictionary.Example:
Output:
- Explanation: The
items()
method returns a view of the dictionary's key-value pairs as tuples, which can be iterated over in a loop to access both keys and values.
- Explanation: The
Last updated on -