Tuples
A tuple in Python is similar to a list. The difference between the two is that we cannot change the elements of a tuple once it is assigned whereas we can change the elements of a list.
In short, a tuple is an immutable list. A tuple can not be changed in any way once it is created.
Characterstics
- Ordered
- Unchangeble
- Allows duplicate
Plan of attack
- Creating a Tuple
- Accessing items
- Editing items
- Adding items
- Deleting items
- Operations on Tuples
- Tuple Functions
Creating Tuples
Example 1
Explanation
- Creates an empty tuple using parentheses and prints it
- Demonstrates that writing
(2)creates an integer, not a tuple, then shows correct syntax with trailing comma(2,)to create a single-item tuple - Shows how to create homogeneous tuples with same data types and heterogeneous tuples with mixed data types including nested lists
- Creates a nested tuple by embedding another tuple inside a tuple
- Uses the
tuple()constructor to convert a string into a tuple of individual characters
Output
Accessing Items
- Indexing
- Slicing
Example 2
Explanation
- Prints the entire tuple
t3to display all its elements - Prints the first element of tuple
t3using index[0] - Prints the last element of tuple
t3using negative indexing[-1] - Uses tuple indexing to access specific elements by position
- Output shows the complete tuple contents followed by individual first and last elements
Output
Example 3
Explanation
- Prints first two elements of t3 using slice notation [0:2]
- Prints every other element from index 0 to 4 using step size 2 with [0:4:2]
- Prints last three elements excluding the final one using negative indexing [-3:-1]
- Prints entire t3 in reverse order using slice with step -1 and no bounds [::-1]
Output
Example 4
Explanation
- This code accesses the last element of a variable named
t5using negative indexing[-1], then accesses the first element of that last element with[0] - It prints the value at position
[0]of the final item in the sequence stored int5 - The
print()function displays the result to the console output - Key APIs/functions used: negative indexing
[-1], positive indexing[0], andprint() - Expected side effect is displaying a single value to stdout, assuming
t5contains nested sequences with at least one element
Output
Editing Items
Example 5
Explanation
- Prints the value of variable
t3to the console - Assigns the value 100 to the element at index 3 of
t3 - Assumes
t3is a mutable sequence type like a list (since it supports item assignment) - The print statement shows the original content before modification
- After execution,
t3will have its fourth element changed to 100
Output
Adding Items
Example 6
Explanation
- Prints the current state of variable
t3to the console - Attempts to add the integer
1to the end oft3using theappend()method - The comment "# not possible" suggests that
t3is likely an immutable type like a tuple, which cannot be modified after creation - If
t3is a tuple, this operation would raise an AttributeError since tuples don't have anappendmethod - The output would show the original contents of
t3followed by an error if the append attempt fails
Output
Deleting Items
Example 7
Explanation
- The code first prints the value of variable
t3to the console - Then it deletes the variable
t3from memory using thedelstatement - When trying to print
t3again, it will raise aNameErrorbecause the variable no longer exists - The
delstatement removes the variable name binding, not the object itself if referenced elsewhere - This demonstrates variable deletion and error handling when accessing undefined variables
Output
Example 8
Explanation
- Creates a tuple t3 with elements (1,2,3,4) and prints it to the console
- Attempts to delete the last element of the tuple using del t3[-1] syntax
- This will raise a TypeError because tuples are immutable in Python and cannot be modified after creation
- The print statement will execute successfully showing (1,2,3,4) before the error occurs
- Tuples don't support item deletion or modification operations, only indexing and slicing are allowed
Output
Operations on Tuples
Example 9
Explanation
- Combines two tuples using the + operator to create a new tuple with all elements from both tuples in order
- Uses the * operator to repeat the first tuple three times, creating a new tuple with repeated elements
- The + operation concatenates tuples while the * operation repeats them a specified number of times
- Both operations return new tuple objects without modifying the original tuples
- Output shows (1, 2, 3, 4, 5, 6, 7, 8) followed by (1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4)
Output
Example 10
Explanation
- Checks if value 1 exists in tuple t1 and prints True/False result
- Checks if value 8 does not exist in tuple t2 and prints True/False result
- Uses
inandnot inoperators to test membership in tuples - These operators return boolean values based on whether elements are present
- Side effect is printing membership test results to console output
Output
Example 11
Explanation
- Loops through each element in the iterable
t1and prints each element on a separate line - Uses Python's
forloop syntax to iterate over items int1 - The
print()function outputs each item to the console with a newline character by default t1is expected to be an iterable like a list, tuple, or string containing multiple elements- Each individual element from
t1gets displayed one at a time in sequential order
Output
Tuple Functions
Example 12
Explanation
- Code performs basic operations on a tuple (1,2,3,4) using built-in Python functions
- Uses len() to get the number of elements, sum() to calculate total, max() and min() to find extremes
- Uses sorted() with reverse=True parameter to return elements in descending order
- Expected output shows length 4, sum 10, max 4, min 1, and reversed sorted list [4,3,2,1]
- All operations work on immutable tuple without modifying original data structure
Output
Example 13
Explanation
- The code creates a tuple named
tcontaining the elements (1,2,2,3,4) - It uses the tuple method
.count()to count occurrences of specific values in the tuple t.count(5)searches for the value 5 in the tuple and returns 0 since 5 is not presentt.count(2)searches for the value 2 in the tuple and returns 2 since 2 appears twice- The code prints two results: first 0 (for count of 5), then 2 (for count of 2)
Output
Example 14
Explanation
- The code creates a tuple named
tcontaining four integer values: 100, 200, 300, and 400 - It uses the tuple method
.index()to find the position of the value 200 within the tuple - The
.index()method searches for the first occurrence of the specified value and returns its index position - Since 200 is at the second position (index 1) in the tuple, the output will be the number 1
- The code prints the result of the
.index()method call to the console
Output
Difference between Lists and Tuples
- Syntax
- Mutability
- Speed
- Memory
- Built in functionality
- Error prone
- Usability
Example 15
Explanation
- Code creates a large list and tuple with 100 million elements each to compare their performance
- Uses time module to measure execution time of iterating through both data structures
- Iterates over each element multiplying by 5 but doesn't store results (just performs calculation)
- Demonstrates that tuples are faster than lists for iteration due to being immutable and more memory efficient
- Shows significant time difference between list and tuple iteration in the print output
Output
Example 16
Explanation
- Code compares memory usage between a list and tuple containing the same elements (0 to 999)
- Uses
sys.getsizeof()function to measure and return the byte size of each data structure - Creates a list with
list(range(1000))and tuple withtuple(range(1000)) - Prints two lines showing the memory footprint of each structure in bytes
- Expected output shows that tuples typically use less memory than lists due to their immutable nature
Output
Example 17
Explanation
- Creates tuple
awith values (1,2,3) and assigns reference tob, so both variables point to same tuple object initially - Reassigns
ato new tuple by concatenating it with (4,), creating a new tuple object rather than modifying existing one - Prints the new tuple (1,2,3,4) for variable
aafter concatenation operation - Prints original tuple (1,2,3) for variable
bsince it still references the original immutable tuple object - Demonstrates that tuples are immutable in Python and reassignment creates new objects rather than modifying existing ones
Output
Why use tuple?
Special Syntax
Example 18
Explanation
- Assigns values from tuple (1,2,3) to variables a, b, and c using tuple unpacking
- Uses the assignment operator = to simultaneously assign multiple values
- Prints the three variables separated by spaces, showing their assigned values
- Key API/function: tuple unpacking syntax with multiple assignment
- Output: 1 2 3 on a single line
Output
Example 19
Explanation
- Code unpacks tuple (1,2,3) into variables a and b, but only assigns first two values
- Uses tuple unpacking syntax to simultaneously assign multiple variables
- Variable a gets value 1, variable b gets value 2 from the tuple
- Third value 3 from tuple is ignored since there's no corresponding variable
- Prints output "1 2" to console
Output
Example 20
Explanation
- Initializes two variables
aandbwith values 1 and 2, respectively. - Swaps the values of
aandbusing tuple unpacking, soabecomes 2 andbbecomes 1. - Uses the
printfunction to output the new values ofaandb. - Expected output is
2 1, displaying the swapped values.
Output
Example 21
Explanation
- Unpacks a tuple
(1, 2, 3, 4)into variablesa,b, andothers, whereagets the first value,bgets the second, andotherscollects the remaining values. - The variable
awill hold the value1,bwill hold2, andotherswill be a list containing[3, 4]. - The
printstatements output the values ofa, , and to the console.
Output
Example 22
Explanation
- The code creates two tuples,
aandb, containing integers. - It uses the
zip()function to combine the tuples element-wise into pairs. - The first
print()statement converts the zipped object into a tuple and outputs it. - The second
print()statement converts the zipped object into a list and outputs it. - The expected output is
((1, 5), (2, 6), (3, 7), (4, 8))for the tuple and[(1, 5), (2, 6), (3, 7), (4, 8)]for the list.
Output
Sets
A set is an unordered collection of items. Every set element is unique (no duplicates) and must be immutable (cannot be changed).
However, a set itself is mutable. We can add or remove items from it.
Sets can also be used to perform mathematical set operations like union, intersection, symmetric difference, etc.
Characterstics:
- Unordered
- Mutable
- No Duplicates
- Can't contain mutable data types
Creating sets
Example 23
Explanation
- Initializes an empty dictionary and prints it along with its type, confirming it's a
dict. - Creates an empty set and prints it along with its type, confirming it's a
set. - Demonstrates that sets can contain unique, immutable items by printing a set of integers and a heterogeneous set containing different data types.
- Shows that sets cannot contain mutable items like another set by commenting out a line that attempts to do so.
- Converts a list to a set to demonstrate type conversion and prints the resulting set, which automatically removes duplicates.
Output
Example 24
Explanation
- The code attempts to create a set
s6containing integers and a nested set. - Sets in Python cannot contain mutable items, such as other sets or lists.
- The code will raise a
TypeErrorwhen trying to creates6due to the inclusion of the nested set{4,5,6}. - The
print(s6)statement will not execute because of the error, so no output will be produced.
Output
Example 25
Explanation
- Creates two sets,
s1ands2, containing the same integers in different orders. - Uses the equality operator
==to compare the two sets. - Sets in Python are unordered collections, so the order of elements does not affect equality.
- The output of the
printstatement will beTrue, indicating that both sets are equal.
Output
Accessing Items
Example 26
Explanation
- The code defines a set
s1containing the integers 1, 2, 3, and 4. - Sets in Python are unordered collections, meaning they do not support indexing like lists or tuples.
- The line
s1[0]attempts to access the first element of the set, which will raise aTypeError. - The expected output is an error message indicating that 'set' object is not subscriptable.
Output
Editing Items
Example 27
Explanation
- The code attempts to modify the first element of the set
s1by assigning100tos1[0]. - Sets in Python are unordered collections and do not support indexing, so this line will raise a
TypeError. - The key function being misused here is indexing, which is not applicable to sets.
- The expected output is an error message indicating that 'set' object is not subscriptable.
Output
Adding Items
Example 28
Explanation
- Creates a set s with elements 1, 2, 3, 4 and then adds single element 5 using add() method
- Prints the set after adding 5, showing {1, 2, 3, 4, 5}
- Uses update() method to add multiple elements [5, 6, 7] to the set
- Prints the set after update, showing {1, 2, 3, 4, 5, 6, 7} (duplicates automatically removed)
- Set data structure automatically handles duplicate removal when adding elements
Output
Deleting Items
Example 29
Explanation
- The code creates a set named
scontaining elements 1, 2, 3, 4, 5 and prints it - The
delstatement deletes the variablesfrom memory, removing the reference to the set - After deletion, attempting to print
sraises aNameErrorbecause the variable no longer exists - The
delkeyword is used to remove variables, items from sequences, or keys from dictionaries - This demonstrates that
delcompletely removes the variable binding, not just its contents
Output
Example 30
Explanation
- Creates a set s with elements 1,2,3,4,5 and then removes element 3 using discard() method
- The discard() method removes the specified element from the set if it exists, but doesn't raise an error if the element is not found
- First print statement outputs {1, 2, 4, 5} after removing 3
- Second discard(100) call doesn't remove anything since 100 isn't in the set, but also doesn't raise an exception
- Final print statement outputs {1, 2, 4, 5} showing the set remains unchanged after trying to discard non-existent element
Output
Example 31
Explanation
- Creates a set with elements 1,2,3,4,5 and removes the element 3 from it
- Uses the
.remove()method which deletes an specified element from the set - When trying to remove non-existent element 100, raises a KeyError exception
- Set s becomes {1,2,4,5} after first remove operation
- Second remove operation causes program to crash with KeyError since 100 is not in the set
Output
Example 32
Explanation
- The code creates a set containing integers 1 through 5, then removes and returns an arbitrary element from the set using the pop() method
- The pop() method removes and returns a random element from the set since sets are unordered collections
- The print statement displays the remaining elements in the set after one element has been removed
- Key function used is the built-in set.pop() method which modifies the original set in-place
- Expected output shows the set with one element removed, but the specific element removed is unpredictable due to set's unordered nature
Output
Example 33
Explanation
- The code creates a set named
scontaining the integers 1 through 5 - The
.clear()method is called on the set, which removes all elements from the set - After clearing, the set becomes empty (contains no elements)
- The
print(s)statement outputs the empty set, which displays asset() - This demonstrates how to completely empty a set in Python by removing all its items
Output
Set Operation
Example 34
Explanation
- Creates two sets with integer values and performs various set operations using operators
- Uses union (
|), intersection (&), difference (-), and symmetric difference (^) operators to combine or compare sets - Tests membership with
inandnot inoperators to check if elements exist in the set - Iterates through the first set printing each element on a separate line
- Output shows combined unique elements for union, shared elements for intersection, different elements for differences, and swapped elements for symmetric difference
Output
Set Functions
Example 35
Explanation
- Code creates a set with numbers 3,1,4,5,2,7 and demonstrates basic set operations
- Uses built-in functions len() to get set size, sum() to add all elements, max() and min() to find extremes
- sorted() function returns a new list with elements in descending order (reverse=True parameter)
- Set s remains unchanged after all operations since sets are immutable
- Output shows: 6 (length), 22 (sum), 7 (max), 1 (min), [7, 5, 4, 3, 2, 1] (sorted descending)
Output
Example 36
Explanation
- Creates two sets s1 and s2 with overlapping elements, then uses the union method to combine all unique elements from both sets
- The union operation produces a new set containing elements from both s1 and s2 without duplicates
- Uses the update method which modifies s1 in-place by adding all elements from s2 to it
- After update, s1 contains all elements from both original sets while s2 remains unchanged
- Output shows the union result first, then the modified s1 and original s2 sets
Output
Example 37
Explanation
- Code finds common elements between two sets using intersection operation
- Uses set methods
intersection()andintersection_update()to compare sets - First prints the shared elements {4, 5} between s1 and s2
- Second operation modifies s1 in-place to contain only intersection elements
- Original s2 remains unchanged, while s1 now contains only {4, 5}
Output
Example 38
Explanation
- The code demonstrates set difference operations between two sets s1 and s2
difference()method returns a new set with elements present in s1 but not in s2, leaving original sets unchangeddifference_update()modifies the original s1 set in-place by removing elements that are also in s2- First print shows {1, 2, 3} which are elements unique to s1
- After difference_update, s1 becomes {1, 2, 3} while s2 remains unchanged as {4, 5, 6, 7, 8}
Output
Example 39
Explanation
- The code demonstrates set operations using symmetric difference between two sets s1 and s2
symmetric_difference()returns elements that are in either set but not in both (exclusive OR operation)symmetric_difference_update()modifies the first set in-place to contain the symmetric difference- First print shows {1, 2, 3, 6, 7, 8} which are elements unique to each set
- After update, s1 becomes {1, 2, 3, 6, 7, 8} and s2 remains unchanged as {4, 5, 6, 7, 8}
Output
Example 40
Explanation
- Checks if two sets have no elements in common using the isdisjoint() method
- Returns True when sets share no items, False when they share at least one item
- Uses set methods isdisjoint(), issubset(), and issuperset for set relationship comparisons
- First comparison shows False because elements 3 and 4 exist in both sets
- Second comparison shows True because sets have completely different elements
Output
Example 41
Explanation
- Checks if one set is a subset of another using the
issubset()method - Tests two relationships: whether s1 is a subset of s2, and whether s2 is a subset of s1
issubset()returns True if all elements of the first set exist in the second set- First print outputs False because s1 contains elements (1,2) that aren't in s2
- Second print outputs True because all elements of s2 (3,4,5) exist in s1
Output
Example 42
Explanation
- Checks if one set contains all elements of another set using the
issuperset()method - First prints
Truebecause s1 contains all elements of s2 (3,4,5 are in both sets) - Second prints
Falsebecause s2 does not contain all elements of s1 (s2 is missing 1,2) - Uses Python's built-in set data structure and its
issuperset()API method - Sets s1 and s2 are created with integer elements using curly brace syntax
Output
Example 43
Explanation
- Creates two separate sets s1 and s2 with identical elements {1,2,3,4,5}
- Uses the copy() method to create a shallow copy of s1 and assign it to s2
- Both sets contain the same values but exist as independent objects in memory
- Prints both sets to show they have identical content
- The copy operation ensures modifying one set won't affect the other set
Output
Frozenset
Frozen set is just an immutable version of a Python set object
Example 44
Explanation
- Creates an immutable set data structure called frozenset containing elements 1, 2, and 3
- Uses the frozenset() constructor function to convert a list into an immutable set
- The frozenset is printed/returned as the final value of the expression
- Key characteristic: frozensets cannot be modified after creation (no add/remove operations allowed)
- Output displays the frozenset as
frozenset({1, 2, 3})showing its immutable nature
Output
Example 45
Explanation
- Creates two immutable sets (frozensets) containing integers 1,2,3 and 3,4,5 respectively
- Uses the pipe operator (|) to perform a union operation between the two frozensets
- Combines all unique elements from both sets into a new frozenset
- Result is a frozenset containing elements 1,2,3,4,5 in no particular order
- The original frozensets remain unchanged since they are immutable
Output
Example 46
Explanation
- Adds the integer value 5 to the data structure represented by fs1
- Uses the add method to insert an element into whatever collection fs1 represents
- The specific behavior depends on what type of data structure fs1 is (could be set, heap, or custom class)
- No return value is expected from this operation
- Side effect is that fs1 now contains the value 5 in its collection
Output
Example 47
Explanation
- The code cell contains comments indicating the functionality of certain operations related to reading and writing data.
- It specifies that all read functions are operational, meaning data can be successfully retrieved.
- It notes that write operations are not functioning, implying that data cannot be saved or modified.
- There are no executable code statements; it only provides a status overview of the code's capabilities.
Example 48
Explanation
- Creates a
frozensetnamedfscontaining integers and anotherfrozensetas an element, demonstrating the use of immutable sets in Python. - The outer
frozensetcontains the elements1,2, and a nestedfrozensetcontaining3and4. frozensetis used here to ensure that the set cannot be modified after creation, providing a hashable type that can be used as a key in dictionaries or elements in other sets.- The output of the code cell will display the
frozensetstructure:frozenset({1, 2, frozenset({3, 4})}).
Output
Set Comprehension
Example 49
Explanation
- Creates a set comprehension that generates a set of integers from 1 to 10.
- Uses the
range()function to create a sequence of numbers starting from 1 up to, but not including, 11. - The curly braces
{}indicate that the output will be a set, which automatically removes any duplicate values. - The expected output is a set containing the integers {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}.
Output
Dictionary
Dictionary in Python is a collection of keys values, used to store data values like a map, which, unlike other data types which hold only a single value as an element.
In some languages it is known as map or assosiative arrays.
dict = { 'name' : 'nitish' , 'age' : 33 , 'gender' : 'male' }
Characterstics:
- Mutable
- Indexing has no meaning
- keys can't be duplicated
- keys can't be mutable items
Create Dictionary
Example 50
Explanation
- Initializes and prints an empty dictionary
d, which outputs{}. - Creates and prints a 1D dictionary
d1with string keys and values, resulting in{'name': 'madhu', 'gender': 'male'}. - Constructs and prints a dictionary
d2with mixed key types (tuple and string), yielding{(1, 2, 3): 1, 'hello': 'world'}. - Defines and prints a 2D dictionary
scontaining personal and academic information, producing a structured output with nested dictionaries.
Output
Example 51
Explanation
- Creates a dictionary
d4using thedict()function with a list of tuples, where each tuple represents a key-value pair. - The first dictionary contains integer keys and values:
{1: 1, 2: 2, 3: 3}. - Prints the first dictionary to the console.
- Reassigns
d4to a new dictionary with mixed key types (strings and integers):{'name': 'madhu', 'age': 32, 3: 3}. - Prints the second dictionary to the console.
Output
Example 52
Explanation
- Creates a dictionary
d5with duplicate keys, where the second key-value pair overwrites the first. - The key
'name'is assigned the value'dadi', as dictionaries cannot have duplicate keys. - Uses the
print()function to output the contents of the dictionary. - The expected output is
{'name': 'dadi'}, showing only the last assigned value for the duplicate key.
Output
Example 53
Explanation
- Creates a dictionary
d6with a string key'name'and a tuple key(1,2,3)associated with the value1. - Prints the first dictionary, showing the output:
{'name': 'madhu', (1, 2, 3): 1}. - Reassigns
d6with a new value for the tuple key(1,2,3), now associated with the tuple(1,2). - Prints the updated dictionary, showing the output:
{'name': 'madhu', (1, 2, 3): (1, 2)}. - Demonstrates that tuples can be used as keys in a dictionary because they are immutable.
Output
Accessing items
Example 54
Explanation
- Code accesses dictionary values using bracket notation and get() method to retrieve the age value
- Uses get() method which safely retrieves values without raising KeyError if key doesn't exist
- Attempts to access nested dictionary key 'maths' but will cause NameError since variable s is not defined
- Prints the value 26 twice using different dictionary access methods
- The last line contains an undefined variable reference that would throw an error at runtime
Output
Adding key-value pair
Example 55
Explanation
- Adds a new key-value pair 'gender': 'male' to dictionary d4 and prints the updated dictionary
- Adds another key-value pair 'weight': 51 to the same dictionary d4 and prints it again
- Accesses a nested dictionary structure s and updates the value at s['subjects']['ds'] to 75
- Prints the modified nested dictionary s after updating the data science subject score
- The code demonstrates how to add new keys to dictionaries and modify nested dictionary values in place
Output
Remove key-value pair
Example 56
Explanation
- Creates a dictionary with three key-value pairs including a string key, integer key, and integer value
- Uses pop() method to remove and return value for key '3', then prints remaining dictionary
- Uses popitem() method to remove and return last inserted key-value pair, then prints remaining dictionary
- Uses del statement to remove key 'name' from dictionary, then prints remaining dictionary
- Calls clear() method to remove all items from dictionary, then prints empty dictionary
- Attempts to print undefined variable 's' and delete nested key 'maths' from 's', but will raise NameError since 's' is not defined
Output
Editing key-value pair
Example 57
Explanation
- This code assigns the value 50 to the key 'ds' within the 'subjects' dictionary that's inside the dictionary variable 's'
- It uses nested dictionary key access syntax with square brackets to set a specific value
- The assignment modifies the original dictionary 's' in-place by adding or updating the 'ds' key
- No return value is explicitly shown since the last line just prints the entire dictionary 's'
- The side effect is that the dictionary 's' now contains {'subjects': {'ds': 50}} if it didn't have 'subjects' before
Output
Dictionary Operations
- Membership
- Iteration
Example 58
Explanation
- The code prints the value of variable
sto the console - It checks if the string 'madhu' exists as a key in
sand prints True/False result - It checks if the string 'name' exists as a key in
sand prints True/False result - The
inoperator only searches for keys in dictionaries, not values - Expected output shows the dictionary content followed by boolean results for key existence checks
Output
Example 59
Explanation
- Code iterates through dictionary keys and prints each key-value pair
- Uses basic for loop syntax to access dictionary items
- Key function is dictionary iteration which yields keys by default
- Expected output shows name: madhu, gender: male, age: 33 on separate lines
- Side effect is printing these key-value pairs to console output
Output
Dictionary Functions
Example 60
Explanation
- Prints the length of variable
dwhich shows how many elements it contains - Displays the contents of
din its current state - Shows
dsorted in descending order using thesorted()function withreverse=Trueparameter - Finds and prints the minimum value in
dusing themin()function - Finds and prints the maximum value in
dusing themax()function, which compares elements by ASCII values for strings
Output
Example 61
Explanation
- This code displays the contents of a dictionary variable
dand its various components - It uses three dictionary methods:
.items()returns key-value pairs as tuples,.keys()returns all keys, and.values()returns all values - The output shows the full dictionary first, then separately prints the items, keys, and values in structured formats
- Each method call creates a view object containing the respective dictionary elements
- The side effect is printing these different representations of the same dictionary data to the console
Output
Example 62
Explanation
- The code updates dictionary d1 with key-value pairs from dictionary d2
- The update() method modifies d1 in-place by adding new keys and overwriting existing keys with values from d2
- Key 4 exists in both dictionaries, so its value changes from 5 to 7 in d1
- Keys 1, 3 remain unchanged while key 6 is added to d1 with value 8
- Output shows the updated dictionary: {1: 2, 3: 4, 4: 7, 6: 8}
Output
Dictionary Comprehension
Example 63
Explanation
- Creates a dictionary comprehension that generates key-value pairs where keys are numbers from 1 to 10 and values are their squares
- Uses
range(1,11)to generate numbers 1 through 10 - Applies the exponentiation operator
**with power 2 to calculate squares - The dictionary comprehension syntax
{key_expression: value_expression for item in iterable}creates the mapping - Output is a dictionary:
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100}
Output
Example 64
Explanation
- Creates a new dictionary by converting kilometers to miles using dictionary comprehension
- Uses the
.items()method to iterate through key-value pairs in the original dictionary - Multiplies each distance value by 0.62 to convert from kilometers to miles
- Key function is dictionary comprehension
{key:value*0.62 for key,value in distances.items()} - Output is a new dictionary with same keys but values converted to miles:
{'delhi': 620.0, 'mumbai': 1240.0, 'bangalore': 1860.0}
Output
Example 65
Explanation
- Creates a dictionary by pairing elements from two lists using zip function
- Maps days of the week to their corresponding temperatures in Celsius
- Uses dictionary comprehension syntax to build the key-value pairs
- zip() function combines corresponding elements from both lists into pairs
- Output is a dictionary with day names as keys and temperature values as values
Output
Example 66
Explanation
- Creates a new dictionary containing only products with positive stock values (greater than 0)
- Uses dictionary comprehension with an if condition to filter items from the original products dictionary
- The
items()method returns key-value pairs that are then filtered based on the conditionvalue>0 - Removes products with zero stock (laptop and tablet) from the resulting dictionary
- Output is
{'phone': 10, 'charger': 32}- only items with remaining inventory
Output
Example 67
Explanation
- Creates a nested dictionary comprehension that generates multiplication tables for numbers 2 through 4
- Uses inner comprehension
{j:i*j for j in range(1,11)}to create tables for each number from 1 to 10 - Outer comprehension
{i:{...} for i in range(2,5)}iterates through numbers 2, 3, and 4 - Each key-value pair maps a number to its complete multiplication table (dictionary of 1-10 multiples)
- Produces a dictionary with keys 2, 3, 4 where each value is another dictionary containing multiplication results
Output
Tuple
###Q1: Join Tuples if similar initial element
While working with Python tuples, we can have a problem in which we need to perform concatenation of records from the similarity of initial element. This problem can have applications in data domains such as Data Science.
For eg.
Example 68
Explanation
- Code groups pairs by their first element and creates lists of second elements for each group
- Uses basic loops and list/set operations to organize data from tuples into nested lists
set()removes duplicates from the first elements of pairs to create unique keysmap(tuple, result)converts nested lists back to tuples for final output- Output shows grouped data where each sublist contains a key followed by all corresponding second values from original pairs
Output
###Q2: Multiply Adjacent elements (both side) and take sum of right and lest side multiplication result.
For eg.
Example 69
Explanation
- Creates a tuple t with values (1, 5, 7, 8, 10) and an empty list L
- Multiplies first two elements (1*5=5) and appends result to L
- Loops through middle elements (index 1 to 3), multiplying each element by its neighbors and adding those products together
- Multiplies last two elements (10*8=80) and appends result to L
- Prints final result as tuple (5, 42, 71, 86, 80)
Output
###Q3: Check is tuples are same or not?
Two tuples would be same if both tuples have same element at same index
Example 70
Explanation
- Compares two tuples element by element using zip function to pair up corresponding elements
- Uses a flag variable to track whether all elements match between the tuples
- When elements don't match, sets flag to False and breaks out of loop early
- Prints whether the tuples are the same or different based on the final flag value
- Expected output is 't1 and t2 are not same' since elements at index 0 don't match (1 vs 0)
Output
###Q4: Count no of tuples, list and set from a list
Output:
Example 71
Explanation
- Code counts occurrences of different data types (lists, sets, tuples) in a mixed list L and stores counts in output list
- Uses type() function to check data type of each element in L and increments corresponding counter in output
- Processes elements: {'hi', 'bye'} (set), {'Geeks', 'forGeeks'} (set), ('a', 'b') (tuple), ['hi', 'bye'] (list), ['a', 'b'] (list)
- Has a bug in print statement where all three counters show output[0] instead of their respective values
- Expected output shows 2 lists, 2 sets, 1 tuple but print formatting is incorrect due to repeated output[0]
Output
###Q5: Shortlist Students for a Job role
Ask user to input students record and store in tuples for each record. Then Ask user to input three things he wants in the candidate- Primary Skill, Higher Education, Year of Graduation.
Show every students record in form of tuples if matches all required criteria.
It is assumed that there will be only one primry skill.
If no such candidate found, print No such candidate
Input:
Output
Example 72
Explanation
- The code collects details of multiple student applicants, including their name, higher education, primary skill, and year of graduation.
- It uses
input()to gather data from the user and stores each applicant's information as a tuple in a list calledstudents. - After collecting the data, it prompts the user for specific criteria (required skill, higher education, and year of graduation) to filter candidates.
- A loop checks each applicant against the specified criteria; if a match is found, it prints the applicant's details.
- If no candidates meet the criteria, it outputs "No such candidates."
Output
Set
###Q1: Write a program to find set of common elements in three lists using sets.
Example 73
Explanation
- The code creates three lists of integers and converts them into sets to eliminate duplicates and allow for set operations.
- It calculates the intersection of the three sets using the
&operator, which finds common elements across all sets. - The result is converted back to a list and printed, showing the elements that are present in all three original lists.
- The expected output will be a list of integers that are common to
ar1,ar2, andar3.
Output
###Q2: Write a program to count unique number of vowels using sets in a given string. Lowercase and upercase vowels will be taken as different.
Input:
Output:
Example 74
Explanation
- Code creates a set of vowels (both lowercase and uppercase) and another set from a string, then finds their intersection to count unique vowels
- Uses set operations with
&operator to find common elements between two sets - The
set()function converts strings into collections of unique characters - Prints the number of unique vowels found in the given string (output will be 6)
- Side effect is displaying the count of distinct vowel letters present in the sample text
Output
Q3: Write a program to Check if a given string is binary string of or not.
A string is said to be binary if it's consists of only two unique characters.
Take string input from user.
Example 75
Explanation
- Code checks if string "Madhu" has exactly 2 unique characters by converting it to a set and measuring its length
- Uses
set()function to extract unique characters from the string,len()to count them, and==comparison - The string "Madhu" contains characters {'M', 'a', 'd', 'h', 'u'} which equals 5 unique characters
- Since 5 does not equal 2, the condition fails and prints 'not binary'
- Side effect is printing 'not binary' to console output
Output
Q4: find union of n arrays.
Example 1:
Input:
Output:
Example 76
Explanation
- The code initializes a list of lists
L, containing integers. - It creates an empty set
sto store unique integers from the lists. - The
forloop iterates through each sublist inL, usingset.update()to add elements tos, ensuring uniqueness. - Finally, it prints the set
s, which contains all unique integers from the original list of lists. - The expected output is a set of unique integers, e.g.,
{1, 2, 3, 4, 5, 6, 7, 9}.
Output
Q5: Intersection of two lists. Intersection of two list means we need to take all those elements which are common to both of the initial lists and store them into another list. Only use using list-comprehension.
Example 1:
Input:
Output:
Example 2:
Input:
Output:
Example 77
Explanation
- The code creates two sets,
lst1andlst2, containing unique integers. - It uses a list comprehension to iterate over
lst1and checks if each item is also inlst2. - The result is a list of items that are common to both sets.
- The expected output is a list containing the elements
[10, 9, 5, 4], which are the intersection oflst1andlst2.
Output
Dictionary
Q1: Key with maximum unique values
Given a dictionary with values list, extract key whose value has most unique values.
Example 1:
Input:
Output:
Example 2:
Input:
Output:
Example 78
Explanation
- Code finds the dictionary key with the most unique values among all lists
- Uses
set()to remove duplicates from each list andlen()to count unique elements - Iterates through dictionary keys to compare unique value counts
- Stores the key with highest unique count in
max_keyvariable - Prints the key name that has the most distinct values across its list
Output
Q2: Replace words from Dictionary. Given String, replace it’s words from lookup dictionary.
Example 1:
Input:
Output:
Example 2:
Input:
Output:
Example 79
Explanation
- The code replaces specific words in a string using a dictionary mapping
- It splits the input string into individual words and checks each word against the replacement dictionary
- Words found in the dictionary get replaced with their corresponding values, while others remain unchanged
- The
split()method breaks the string into words, andjoin()combines them back into a single string - Output is: "Blog is the best channel for Data-Science students."
Output
Q3: Convert List to List of dictionaries. Given list values and keys list, convert these values to key value pairs in form of list of dictionaries.
Example 1:
Input:
Output:
Example 2:
Input:
Output:
Example 80
Explanation
- Initializes a list
test_listcontaining mixed data types and akey_listwith two keys. - Calculates the length of
test_listand initializes an empty listresto store the results. - Iterates over
test_listin steps of 2, creating a dictionary for each pair of elements using keys fromkey_list. - Appends each created dictionary to the
reslist. - Outputs a list of dictionaries, where each dictionary maps keys from
key_listto corresponding values fromtest_list.
Output
Q4: Convert a list of Tuples into Dictionary.
Example 1:
Input:
Output:
Example 2:
Input:
Output:
Example 81
Explanation
- Initializes a list
L1containing tuples of names and corresponding numbers, and another listLwhich is not used in the code. - Creates an empty dictionary
dto store names as keys and their associated numbers as values in a list. - Iterates over each tuple in
L1, assigning the name as the key and the number as a single-element list value in the dictionary. - The
print(d)statement outputs the dictionaryd, which maps names to their respective numbers. - The expected output is:
{'akash': [10], 'gaurav': [12], 'anand': [14], 'suraj': [20], 'akhil': [25], 'ashish': [30]}.
Output
Q5: Sort Dictionary key and values List.
Example 1:
Input:
Output:
Example 2:
Input:
Output:
Example 82
Explanation
- Initializes a dictionary
dwith keys as letters and values as lists of integers. - Iterates over the keys of the dictionary in sorted order, printing each key and its corresponding list.
- Sorts the list associated with each key and stores the sorted list in a new dictionary
res. - Finally, prints the
resdictionary containing the sorted lists for each key. - Expected output includes the printed keys, their original lists, and the final sorted dictionary.
Output

