Notes on Tuples and Dictionaries
10.1 Introduction to Tuples
A tuple is an ordered sequence of elements which can contain different data types such as integers, floats, strings, lists, or even other tuples. Tuples are enclosed in parentheses and are separated by commas. For example:
# Tuple of integers
tuple1 = (1, 2, 3, 4, 5)
# Tuple of mixed data types
tuple2 = ('Economics', 87, 'Accountancy', 89.6)
Key Characteristics:
- Tuples can be accessed using indexing and slicing.
- A single element tuple requires a comma after the element to differentiate it from a regular data type.
- Tuples are immutable, meaning their contents cannot be changed once created. Attempting to modify a tuple will raise an error:
tuple1[4] = 10 # Raises TypeError: 'tuple' object does not support item assignment
Concatenation and Repetition:
- Concatenation can combine two tuples using
+:
tuple1 + tuple2 # Results in a new tuple
- Repetition allows tuples to be repeated using
*:
tuple1 * 3 # Repeats tuple elements three times
Membership Testing:
- You can check for the presence of an element using
in keyword. It returns True if present, otherwise False.
'Green' in tuple1 # Returns True or False
Tuple Methods and Built-in Functions:
Common tuple methods include:
- len(): Returns the number of items in a tuple.
- count(): Counts occurrences of an element.
- index(): Returns the index of the first occurrence of an element.
- min(), max(), and sorted() provide statistics and ordering.
10.2 Tuple Operations
- Indexing: Accessing an element using its index (starting from 0).
- Slicing: Extracting a subset of a tuple using range of indices.
tuple1[2:5] # Slices to get a subset from index 2 to 4
10.3 Tuple Assignment and Nested Tuples
- You can unpack tuples into variables:
(a, b) = (1, 2) # Assigns 1 to a and 2 to b
- Nested tuples contain other tuples as elements, useful for structuring complex data.
10.4 Introduction to Dictionaries
A dictionary is a mutable, unordered collection of key-value pairs. Each key is unique and is associated with a value. You can create dictionaries using {} brackets:
dict_example = {'name': 'John', 'age': 25}
Key Characteristics:
- Mutable: The contents can be altered after creation.
- Keys must be unique and of an immutable type, whereas values can be of any data type.
- Accessing values is done via keys:
age = dict_example['age']
Dictionary Operations:
dict_example['salary'] = 50000 # Adds a new key-value pair
- Modifying existing items:
dict_example['age'] = 30 # Updates the value associated with 'age'
- Membership testing for keys:
'age' in dict_example # Returns True or False
10.5 Dictionary Methods
Common dictionary methods include:
- keys(): Returns all keys in the dictionary.
- values(): Returns all values in the dictionary.
- items(): Returns all the key-value pairs as tuples.
- get(): Retrieves the value for a given key, returning
None if the key doesn't exist.
- update(): Updates dictionary with a new key-value pair from another dictionary.
Summary of Key Concepts:
- Tuples are immutable sequences, while dictionaries are mutable collections of key-value pairs.
- Both data structures allow for ordering and access methods, but they serve different purposes and constraints in programming with Python.
- Remember to use tuples for fixed collections of items, and dictionaries for mapping relationships between unique keys and dynamic values.
Exercises:
Practice with tuples and dictionaries includes retrieving indices, checking membership, modifying values, and using built-in methods for sorting and counting, as well as creating dictionaries from key-value pairs based on program input.