Tuples and Dictionaries
Tuples and Dictionaries — Study Notes
NCERT-aligned · 17 notes · 3 shown free
10.1 INTRODUCTION TO TUPLES
Explanation10.1 INTRODUCTION TO TUPLES
A tuple is an ordered sequence of elements that can be of different data types such as integer, float, string, list, or even another tuple. Tuples are enclosed in parentheses (round brackets) and elements are separated by commas. Similar to lists and strings, elements of a tuple can be accessed using index values starting from 0. Tuples are particularly useful when you want to store a collection of heterogeneous data items. For example, a tuple can contain a student's name (string), roll number (integer), and marks (float) all together. Unlike lists, tuples are immutable, meaning once created, their elements cannot be changed. This immutability makes tuples faster and safer to use when the data should not be modified. If a tuple contains only a single element, it must be followed by a comma; otherwise, Python treats it as the data type of the element itself, not as a tuple. For example, (20) is treated as an integer, but (20,) is treated as a tuple with one element. Also, a sequence of comma-separated elements without parentheses is treated as a tuple by default. Tuples can also contain mutable elements like lists. Even though the tuple itself is immutable, the mutable elements inside it can be modified. This feature allows for flexible data structures combining immutability and mutability. Examples: - tuple1 = (1, 2, 3, 4, 5) # tuple of integers - tuple2 = ('Economics', 87, 'Accountancy', 89.6) # tuple of mixed data types - tuple3 = (10, 20, 30, [40, 50]) # tuple containing a list - tuple4 = (1, 2, 3, 4, 5, (10, 20)) # nested tuple Tuples are preferred over lists when the data is not supposed to change throughout the program, ensuring data integrity and faster access.
- Tuple is an ordered sequence of elements enclosed in parentheses.
- Elements can be of different data types including integers, floats, strings, lists, or tuples.
- Indexing starts at 0 and elements can be accessed using indices.
- Tuples are immutable; their elements cannot be changed after creation.
- Single element tuples require a trailing comma to be recognized as tuples.
- A sequence without parentheses but with commas is treated as a tuple by default.
- 📌 Tuple: An ordered, immutable sequence of elements.
- 📌 Immutable: Cannot be changed after creation.
- 📌 Indexing: Accessing elements by position starting at 0.
10.1.1 Accessing Elements in a Tuple
Explanation10.1.1 Accessing Elements in a Tuple
Elements in a tuple can be accessed using indexing and slicing, similar to lists and strings. Indexing starts at 0 for the first element and can be positive or negative. Positive indices count from the start (0, 1, 2, ...), while negative indices count from the end (-1, -2, -3, ...). Accessing elements using indices allows retrieval of individual elements. For example, tuple1[0] returns the first element, and tuple1[-1] returns the last element. If an index is out of range, Python raises an IndexError. Slicing allows accessing a range of elements by specifying start and end indices: tuple1[start:end]. The slice includes elements from the start index up to but not including the end index. Omitting start or end defaults to the beginning or end of the tuple respectively. Slicing also supports a step parameter to skip elements. Examples: - tuple1 = (2, 4, 6, 8, 10, 12) - tuple1[0] returns 2 - tuple1[3] returns 8 - tuple1[-1] returns 12 - tuple1[2:7] returns (30, 40, 50, 60, 70) - tuple1[0:len(tuple1):2] returns every second element starting from index 0 - tuple1[::-1] returns the tuple in reverse order Attempting to access an index that does not exist results in an IndexError, ensuring safe access.
- Indexing starts at 0 and can be positive or negative.
- Positive indices count from the start; negative indices count from the end.
- Slicing extracts a range of elements using start:end syntax.
- Omitting start or end in slicing defaults to beginning or end of the tuple.
- Step parameter in slicing allows skipping elements.
- Accessing out-of-range indices raises IndexError.
- 📌 Indexing: Accessing elements by their position.
- 📌 Slicing: Extracting a subset of elements from a sequence.
- 📌 Step: The interval between elements in slicing.
10.1.2 Tuple is Immutable
Explanation10.1.2 Tuple is Immutable
Tuples are immutable data types in Python, meaning that once a tuple is created, its elements cannot be changed, added, or removed. Attempting to assign a new value to an element of a tuple results in a TypeError. Example: - tuple1 = (1, 2, 3, 4, 5)
Practice Questions — Tuples and Dictionaries
Includes NCERT exercise questions with answers
Q1.1. Consider the following tuples, tuple1 and tuple2: tuple1 = (23,1,45,67,45,9,55,45) tuple2 = (100,200) Find the output of the following statements: i. print(tuple1.index(45)) ii. print(tuple1.count(45)) iii. print(tuple1 + tuple2) iv. print(len(tuple2)) v. print(max(tuple1)) vi print(min(tuple1)) vii. print(sum(tuple2)) viii. print(sorted(tuple1)) print(tuple1)
Answer:
Given: tuple1 = (23,1,45,67,45,9,55,45) tuple2 = (100,200) Solutions: i. tuple1.index(45) returns the index of the first occurrence of 45 in tuple1. tuple1 = (23,1,45,67,45,9,55,45) The first 45 is at index 2 (0-based indexing). Output: 2 ii. tuple1.count(45) counts how many times 45 appears in tuple1. 45 appears 3 times. Output: 3 iii. tuple1 + tuple2 concatenates the two tuples. Output: (23,1,45,67,45,9,55,45,100,200) iv. len(tuple2) gives the length of tuple2. tuple2 has 2 elements. Output: 2 v. max(tuple1) gives the maximum value in tuple1. Values: 23,1,45,67,45,9,55,45 Maximum is 67. Output: 67 vi. min(tuple1) gives the minimum value in tuple1. Minimum is 1. Output: 1 vii. sum(tuple2) sums all elements in tuple2. 100 + 200 = 300 Output: 300 viii. sorted(tuple1) returns a sorted list of tuple1 elements. Sorted: [1, 9, 23, 45, 45, 45, 55, 67] Output: [1, 9, 23, 45, 45, 45, 55, 67] print(tuple1) prints the original tuple1. Output: (23, 1, 45, 67, 45, 9, 55, 45)
Explanation:
Step-by-step: - index(45): Find first occurrence index. - count(45): Count occurrences. - + operator: Concatenate tuples. - len(): Number of elements. - max()/min(): Find max/min values. - sum(): Add all elements. - sorted(): Return sorted list. - print(tuple1): Display original tuple.
Q2.2. Consider the following dictionary stateCapital: stateCapital = {"AndhraPradesh": "Hyderabad", "Bihar": "Patna", "Maharashtra": "Mumbai", "Rajasthan": "Jaipur"} Find the output of the following statements: i. print(stateCapital.get("Bihar")) ii. print(stateCapital.keys()) iii. print(stateCapital.values()) iv. print(stateCapital.items()) v. print(len(stateCapital)) vi. print("Maharashtra" in stateCapital) vii. print(stateCapital.get("Assam")) viii. del stateCapital["Rajasthan"] print(stateCapital)
Answer:
Given: stateCapital = {"AndhraPradesh": "Hyderabad", "Bihar": "Patna", "Maharashtra": "Mumbai", "Rajasthan": "Jaipur"} Solutions: i. stateCapital.get("Bihar") returns the value for key "Bihar". Output: Patna ii. stateCapital.keys() returns all keys. Output: dict_keys(['AndhraPradesh', 'Bihar', 'Maharashtra', 'Rajasthan']) iii. stateCapital.values() returns all values. Output: dict_values(['Hyderabad', 'Patna', 'Mumbai', 'Jaipur']) iv. stateCapital.items() returns key-value pairs as tuples. Output: dict_items([('AndhraPradesh', 'Hyderabad'), ('Bihar', 'Patna'), ('Maharashtra', 'Mumbai'), ('Rajasthan', 'Jaipur')]) v. len(stateCapital) returns number of key-value pairs. Output: 4 vi. "Maharashtra" in stateCapital checks if key exists. Output: True vii. stateCapital.get("Assam") returns None as key "Assam" not present. Output: None viii. del stateCapital["Rajasthan"] deletes the key "Rajasthan". After deletion, print(stateCapital) outputs: {'AndhraPradesh': 'Hyderabad', 'Bihar': 'Patna', 'Maharashtra': 'Mumbai'}
Explanation:
Step-by-step: - get(key): Returns value or None if key absent. - keys(): Returns all keys. - values(): Returns all values. - items(): Returns all key-value pairs. - len(): Number of entries. - 'in' operator: Checks key presence. - del: Deletes key-value pair.
Q3.3. "Lists and Tuples are ordered". Explain.
Answer:
Lists and tuples are ordered because the elements have a defined sequence and each element can be accessed by its index. The order in which elements are inserted is preserved. For example, in a list [10, 20, 30], 10 is at index 0, 20 at index 1, and 30 at index 2. Similarly, in a tuple (5, 15, 25), the order is maintained and elements can be accessed by their positions.
Explanation:
Ordered means elements maintain their position and can be accessed via indices. This property allows predictable retrieval and manipulation of elements based on their order.
Q4.4. With the help of an example show how can you return more than one value from a function.
Answer:
In Python, a function can return multiple values by returning them as a tuple. For example: def get_min_max(numbers): return min(numbers), max(numbers) result = get_min_max([10, 20, 30, 40]) print(result) # Output: (10, 40) Here, the function get_min_max returns two values: minimum and maximum of the list. These are returned as a tuple and can be unpacked if needed.
Explanation:
Functions can return multiple values by returning a tuple containing all values. This allows returning more than one result from a single function call.
Q5.5. What advantages do tuples have over lists?
Answer:
Advantages of tuples over lists: 1. Tuples are immutable, so their elements cannot be changed, which makes them safer to use when data should not be modified. 2. Tuples can be used as keys in dictionaries because they are hashable, unlike lists. 3. Tuples generally have faster access and are more memory efficient than lists. 4. Tuples can be used to represent fixed collections of items. These advantages make tuples suitable for storing data that should remain constant.
Explanation:
Immutability provides safety and hashability, enabling use as dictionary keys. Memory efficiency and speed are additional benefits.
Q6.6. When to use tuple or dictionary in Python. Give some examples of programming situations mentioning their usefulness.
Answer:
Use tuples when you need an ordered collection of items that should not change throughout the program. For example, storing coordinates (x, y) of a point, or returning multiple values from a function. Use dictionaries when you need to associate keys with values for fast lookup, insertion, and deletion. For example, storing student names as keys and their marks as values, or mapping country names to their capitals. Examples: - Tuple: Representing RGB color as (255, 0, 0). - Dictionary: Storing phone book entries with names as keys and phone numbers as values.
Explanation:
Tuples are immutable ordered collections useful for fixed data. Dictionaries provide key-value mapping useful for associative arrays and fast data retrieval.
Q7.7. Prove with the help of an example that the variable is rebuilt in case of immutable data types.
Answer:
Example: x = (1, 2, 3) print(id(x)) # Suppose id is 140353 x = x + (4,) print(id(x)) # New id, e.g., 140400 Explanation: Initially, x points to a tuple (1, 2, 3). When we add (4,) to x, a new tuple is created and x now points to this new tuple. The id (memory address) changes, proving that the variable is rebuilt rather than modified in place, which is characteristic of immutable data types like tuples.
Explanation:
Immutable objects cannot be changed after creation; operations create new objects and variables point to these new objects.
Q8.8. TypeError occurs while statement 2 is running. Give reason. How can it be corrected? >>> tuple1 = (5) #statement 1 >>> len(tuple1) #statement 2
Answer:
Reason: In statement 1, tuple1 = (5) is not a tuple but an integer enclosed in parentheses. Hence, tuple1 is an int, and len(tuple1) causes TypeError because integers do not have length. Correction: To create a tuple with one element, a comma is needed: tuple1 = (5,) Now, len(tuple1) will return 1 without error.
Explanation:
Parentheses alone do not make a tuple; a trailing comma is required for single-element tuples.
All 11 Chapters in Computer Science
Computer Science · Class 11