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
Python tuple creation and type handling demonstration
Explanation
- Empty tuples are created using parentheses with no elements, demonstrating the basic syntax for tuple initialization
- Single element tuples require a trailing comma to distinguish them from regular parentheses around a variable, showing the importance of proper tuple syntax
- Tuples can contain mixed data types including numbers, booleans, and nested structures like lists, illustrating their heterogeneous nature
- The tuple() constructor function can convert strings into tuples of individual characters, demonstrating alternative methods for tuple creation
- Type checking reveals that single non-comma elements are treated as their underlying data type rather than tuples, emphasizing the comma requirement for single-element tuples
Output
Accessing Items
- Indexing
- Slicing
Python tuple indexing and element access demonstration
Explanation
- The code snippet demonstrates basic tuple element retrieval using different index positions
- t3[0] accesses the first element of the tuple using zero-based indexing
- t3[-1] retrieves the last element of the tuple using negative indexing
- The print statements show how tuple elements can be accessed individually by their position
- This illustrates fundamental tuple navigation techniques for data extraction
Output
Demonstrating various slicing techniques on a Python tuple
Explanation
- The first line
print(t3[0:2])retrieves and prints the first two elements of the tuplet3. - The second line
print(t3[0:4:2])prints every second element from the first four elements oft3, effectively showing the elements at index 0 and 2. - The third line
print(t3[-3:-1])extracts and prints the elements from the third-to-last to the second-to-last, excluding the last element. - The fourth line
print(t3[::-1])reverses the entire tuplet3and prints it, showcasing the elements in reverse order.
Output
Accessing the first element of the last sublist in a nested list structure
Explanation
- The code snippet uses indexing to retrieve a specific element from a nested list named
t5. t5[-1]accesses the last sublist within the main listt5.- The
[0]index then retrieves the first element of that last sublist. - This operation is useful for quickly obtaining data from complex list structures without needing to iterate through the entire list.
Output
Editing Items
Modifying an element in a Python list and printing its value before the change
Explanation
- The code begins by printing the current value of the list
t3. - The list
t3is then modified by setting the element at index 3 to the value 100. - This operation directly alters the original list, demonstrating how lists are mutable in Python.
- The index used (3) refers to the fourth element of the list, as indexing starts from 0.
Output
Adding Items
Attempting to print and modify a list in Python before its initialization
Explanation
- The code tries to print the variable
t3, which is expected to be a list. - The
appendmethod is called ont3to add the integer1to the list. - If
t3has not been defined prior to this code snippet, it will raise aNameError. - The comment indicates that the append operation is not possible due to the undefined state of
t3. - This snippet highlights the importance of initializing variables before use in Python.
Output
Deleting Items
This code demonstrates variable deletion and the resulting error when accessing a deleted variable in Python.
Explanation
- The code starts by printing the value of the variable
t3. - The
delstatement is used to delete the variablet3, removing it from the current namespace. - After deletion, the code attempts to print
t3again, which will raise aNameErrorsincet3no longer exists. - This snippet illustrates the importance of variable scope and lifecycle in Python programming.
Output
Attempting to modify a tuple in Python demonstrates immutability.
Explanation
- A tuple
t3is created with four integer elements: 1, 2, 3, and 4. - The
printfunction outputs the contents of the tuple to the console. - The
delstatement attempts to remove the last element of the tuple using its index. - This operation will raise a
TypeErrorbecause tuples are immutable, meaning their elements cannot be changed or deleted after creation.
Output
Operations on Tuples
Demonstrating Tuple Concatenation and Repetition in Python
Explanation
- The code defines two tuples,
t1andt2, containing integer elements. - The expression
t1 + t2concatenates the two tuples, resulting in a new tuple that combines their elements. - The expression
t1 * 3repeats the elements oft1three times, creating a new tuple with the elements oft1repeated consecutively. - The
printstatements output the results of both operations to the console.
Output
Checking membership of elements in Python collections using 'in' and 'not in' operators
Explanation
- The code checks if the integer
1is present in the collectiont1using theinoperator. - It prints
Trueif1is found int1, otherwise it printsFalse. - The code also checks if the integer
8is absent from the collectiont2using thenot inoperator. - It prints
Trueif8is not found int2, otherwise it printsFalse. - This demonstrates how to perform membership tests on collections in Python.
Output
This code snippet iterates through a collection and prints each element.
Explanation
- The code uses a
forloop to iterate over the iterablet1. - Each element in
t1is accessed one at a time and assigned to the variablei. - The
print(i)statement outputs the current element to the console. - This loop continues until all elements in
t1have been processed. - It is a simple way to display or process items in a list, tuple, or any iterable.
Output
Tuple Functions
Basic tuple operations in Python for length, sum, min, max, and sorting.
Explanation
- The code initializes a tuple
tcontaining four integers: 1, 2, 3, and 4. len(t)calculates and prints the number of elements in the tuple, which is 4.sum(t)computes and prints the total sum of the elements in the tuple, resulting in 10.max(t)finds and prints the maximum value in the tuple, which is 4.min(t)identifies and prints the minimum value in the tuple, which is 1.sorted(t, reverse=True)sorts the elements of the tuple in descending order and prints the result as a list: [4, 3, 2, 1].
Output
This code snippet demonstrates how to count occurrences of specific elements in a tuple using Python's built-in methods.
Explanation
- A tuple
tis defined containing the elements (1, 2, 2, 3, 4). - The
count()method is called on the tuple to determine how many times the value5appears, which will return0since5is not in the tuple. - The
count()method is then called again to find the occurrences of the value2, which will return2as2appears twice in the tuple. - The results of both
count()method calls are printed to the console.
Output
This code retrieves the index of a specified value in a tuple.
Explanation
- A tuple
tis defined with four integer elements: 100, 200, 300, and 400. - The
index()method is called on the tupletto find the position of the value200. - The method returns the index of the first occurrence of the specified value, which is
1in this case. - The result is printed to the console, displaying the index of the value within the tuple.
Output
Difference between Lists and Tuples
- Syntax
- Mutability
- Speed
- Memory
- Built in functionality
- Error prone
- Usability
Comparing performance between lists and tuples in Python for large datasets
Explanation
- The code imports the
timemodule to measure execution time for operations on lists and tuples. - It creates a list
Land a tupleT, both containing integers from 0 to 99,999,999. - The first timing block iterates over the list
L, multiplying each element by 5, and records the time taken. - The second timing block performs the same operation on the tuple
T, measuring the time for this operation as well. - Finally, it prints the execution time for both the list and the tuple, highlighting the performance differences.
Output
Comparing memory usage of lists and tuples in Python
Explanation
- The code imports the
sysmodule to access system-specific parameters and functions. - It creates a list
Land a tupleT, both containing integers from 0 to 999. - The
sys.getsizeof()function is used to measure the memory size of the list and the tuple. - The sizes of the list and tuple are printed to the console, illustrating the difference in memory consumption between the two data structures.
Output
Understanding tuple reassignment and reference behavior in Python
Explanation
- The variable
ais initially assigned a tuple(1, 2, 3), andbis set to reference the same tuple. - When
ais updated witha + (4,), a new tuple(1, 2, 3, 4)is created, andanow references this new tuple. - The original tuple
(1, 2, 3)remains unchanged and is still referenced byb. - The
print(a)statement outputs the new tuple(1, 2, 3, 4), whileprint(b)outputs the original tuple(1, 2, 3). - This demonstrates how tuples are immutable and how variable reassignment affects references in Python.
Output
Why use tuple?
Special Syntax
This code demonstrates tuple unpacking in Python to assign multiple variables simultaneously.
Explanation
- The code initializes a tuple with three elements: 1, 2, and 3.
- It unpacks the tuple into three variables:
a,b, andc. - The
printfunction outputs the values ofa,b, andc, resulting in "1 2 3". - Tuple unpacking allows for cleaner and more concise code when assigning multiple variables at once.
Output
This code snippet demonstrates tuple unpacking in Python with an incorrect assignment.
Explanation
- The code attempts to unpack a tuple with three elements
(1, 2, 3)into two variablesaandb. - Since there are more values in the tuple than variables to unpack, this will raise a
ValueError. - The
print(a, b)statement is intended to display the values ofaandb, but it will not execute due to the error in unpacking. - To fix the error, either the tuple should have two elements or the number of variables should match the number of elements in the tuple.
Output
Python tuple unpacking and variable swapping technique
Explanation
- The code demonstrates Python's simultaneous assignment feature where two variables are assigned values in a single statement
- The expression a,b = b,a performs a parallel swap by creating a tuple (b,a) and immediately unpacking it into variables a and b
- This approach eliminates the need for a temporary variable typically required in other programming languages for swapping values
- The print statement outputs the swapped values, showing that a now contains 2 and b contains 1
- This idiom is a Pythonic way to exchange variable contents without explicit temporary storage
Output
Python tuple unpacking with starred expression for variable assignment
Explanation
- The code uses extended unpacking syntax to assign values from a tuple to multiple variables simultaneously
- The first two values (1, 2) are assigned to variables
aandbrespectively - The
*otherssyntax captures all remaining values from the tuple into a list - The starred expression allows flexible handling of sequences with unknown length
- This pattern is commonly used when you need specific elements plus all remaining elements from iterable data structures
Output
Combining two tuples into a list and tuple of paired elements using zip in Python
Explanation
- The code defines two tuples,
aandb, containing integers. - The
zipfunction is used to pair elements from both tuples, creating an iterable of tuples. - The first
printstatement converts the zipped object into a tuple, displaying the paired elements as a tuple of tuples. - The second
printstatement converts the zipped object into a list, showing the paired elements as a list of tuples. - This demonstrates how to efficiently combine multiple iterables in Python.
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
Understanding the Creation and Characteristics of Sets in Python
Explanation
- Initializes and prints an empty dictionary and an empty set, demonstrating their types.
- Shows the creation of a one-dimensional set with unique integers and notes the restriction against mutable items.
- Demonstrates the ability to store heterogeneous data types, including integers, strings, floats, booleans, and tuples within a set.
- Illustrates type conversion by creating a set from a list, emphasizing the flexibility of set initialization.
- Highlights that sets automatically discard duplicate values, ensuring all elements remain unique.
Output
Attempting to include mutable items in a Python set results in a TypeError.
Explanation
- The code attempts to create a set
s6that includes a nested set{4, 5, 6}as one of its elements. - In Python, sets can only contain immutable (hashable) items, such as integers, strings, and tuples.
- Since a set is mutable, trying to include it within another set raises a
TypeError. - The
print(s6)statement will not execute successfully due to the error encountered during the set creation. - To fix this, you can use a tuple instead of a set for the nested item, like
{1, 2, 3, (4, 5, 6)}.
Output
This code snippet demonstrates the equality comparison of two sets in Python.
Explanation
- Two sets,
s1ands2, are defined with the same elements but in different orders. - The equality operator
==is used to check if both sets contain the same elements. - Since sets are unordered collections, the comparison evaluates to
Trueregardless of the order of elements. - The result of the comparison is printed to the console.
Output
Accessing Items
Attempting to access an element in a Python set using an index results in an error.
Explanation
- Sets in Python are unordered collections, meaning they do not support indexing like lists or tuples.
- The code snippet tries to access the first element of the set
s1using the index0, which is not valid for sets. - Attempting to run this code will raise a
TypeError, indicating that 'set' object is not subscriptable. - To access elements in a set, you can use iteration or convert the set to a list if indexing is necessary.
Output
Editing Items
Attempting to modify a set in Python results in an error due to its immutable nature.
Explanation
- The code initializes a set
s1containing the integers 1, 2, 3, and 4. - Sets in Python are unordered collections of unique elements, meaning they do not support indexing.
- The line
s1[0] = 100attempts to assign a value to an index, which is not valid for sets. - This will raise a
TypeError, indicating that 'set' object does not support item assignment. - To modify a set, methods like
add()orremove()should be used instead.
Output
Adding Items
Demonstrating the addition and updating of elements in a Python set
Explanation
- A set
sis initialized with the elements 1, 2, 3, and 4. - The
addmethod is used to insert the element 5 into the set, which modifies the set to include this new element. - The updated set is printed, showing the inclusion of 5.
- The
updatemethod is then called with a list containing 5, 6, and 7, which adds these elements to the set. - The final print statement displays the set after the update, reflecting all unique elements.
Output
Deleting Items
This code demonstrates the deletion of a set in Python and the resulting error when accessed afterward.
Explanation
- A set
sis initialized with the values{1, 2, 3, 4, 5}. - The first
print(s)statement outputs the contents of the set. - The
del sstatement removes the reference to the sets. - The second
print(s)statement attempts to accesss, which raises aNameErrorsincesno longer exists.
Output
This code demonstrates the use of the discard method to remove elements from a set without raising an error for non-existent items.
Explanation
- A set
sis initialized with the integers 1 through 5. - The
discardmethod is called to remove the element3from the set, resulting in{1, 2, 4, 5}. - The
printfunction outputs the modified set after the first discard operation. - The
discardmethod is called again with100, which does not exist in the set, but no error is raised. - The final print statement shows that the set remains unchanged as
{1, 2, 4, 5}after attempting to discard a non-existent element.
Output
This code demonstrates the use of the remove method on a set in Python to delete specific elements.
Explanation
- A set
sis initialized with the integers 1 through 5. - The
removemethod is called to delete the element3from the set, which successfully modifies the set to{1, 2, 4, 5}. - The modified set is printed to the console.
- The code attempts to remove the element
100, which is not present in the set, leading to aKeyError. - This illustrates that
removeraises an error if the specified element does not exist in the set.
Output
This code demonstrates the usage of the pop method to remove an arbitrary element from a set in Python.
Explanation
- A set
sis initialized with five integer elements: 1, 2, 3, 4, and 5. - The
pop()method is called on the sets, which removes and returns an arbitrary element from the set. - Since sets are unordered collections, the specific element removed is not predictable.
- The modified set is then printed, showing the remaining elements after the arbitrary removal.
Output
This code snippet demonstrates how to clear all elements from a set in Python.
Explanation
- A set
sis initialized with the elements 1, 2, 3, 4, and 5. - The
clear()method is called on the sets, which removes all elements from it. - After clearing, the set is printed, resulting in an empty set output.
- This method is useful when you want to reset a set without creating a new one.
Output
Set Operation
Demonstrating Set Operations and Membership Testing in Python
Explanation
- The code initializes two sets,
s1ands2, containing distinct integers. - It performs various set operations: union, intersection, difference, and symmetric difference, showcasing how to combine and compare sets.
- Membership tests are conducted to check if specific elements are present in
s1, usinginandnot inkeywords. - A loop iterates through the elements of
s1, printing each value, demonstrating how to traverse a set.
Output
Set Functions
This code snippet demonstrates basic set operations in Python using built-in functions.
Explanation
- The code initializes a set
scontaining unique integers. len(s)returns the number of elements in the set, which is 6.sum(s)calculates the total sum of the elements in the set, resulting in 22.max(s)finds the highest value in the set, which is 7.min(s)identifies the lowest value in the set, which is 1.sorted(s, reverse=True)returns a list of the set elements sorted in descending order: [7, 5, 4, 3, 2, 1].
Output
Merging two sets in Python using union and update methods
Explanation
- The code initializes two sets,
s1ands2, containing distinct integers. - The
unionmethod is called ons1withs2as an argument, which returns a new set containing all unique elements from both sets. - The result of the union operation is printed, showing the combined elements of
s1ands2. - The
updatemethod modifiess1in place by adding all elements froms2, effectively merging the two sets. - Finally, the updated
s1and the originals2are printed, demonstrating thats1now contains all elements from both sets whiles2remains unchanged.
Output
This code demonstrates how to find the intersection of two sets in Python and update one set with the intersection results.
Explanation
- The code initializes two sets,
s1ands2, containing integers. - It uses the
intersectionmethod to compute the common elements betweens1ands2, which are printed as the result. - The
intersection_updatemethod modifiess1to retain only the elements that are also ins2. - After the update, the modified
s1and the originals2are printed, showing the effect of the intersection update.
Output
Demonstrating set operations for finding differences and updating sets in Python
Explanation
- The code initializes two sets,
s1ands2, containing integers. - It uses the
difference()method to compute the elements ins1that are not ins2, printing the result. - The
difference_update()method modifiess1in place, removing elements found ins2. - After the update, the modified
s1and the originals2are printed, showing the effect of the update operation.
Output
Demonstrating the use of symmetric difference and updating sets in Python
Explanation
- The code initializes two sets,
s1ands2, containing distinct integers. - It calculates the symmetric difference between the two sets using the
symmetric_differencemethod, which returns elements that are in either set but not in both. - The result of the symmetric difference is printed, showing
{1, 2, 3, 6, 7, 8}. - The
symmetric_difference_updatemethod is then called ons1, modifying it to contain only the symmetric difference withs2. - Finally, the updated
s1and the originals2are printed, reflecting the changes made tos1.
Output
Understanding the use of set operations to check disjoint sets in Python
Explanation
- The code defines two sets,
s1ands2, and checks if they are disjoint using theisdisjoint()method. - The first check (
s1.isdisjoint(s2)) returnsFalsebecause both sets share common elements (3 and 4). - The second check (
s1.isdisjoint(s2)) returnsTrueas there are no common elements betweens1ands2(1, 2, 3, 4 vs 7, 8, 5, 6). - The
isdisjoint()method is useful for determining if two sets have no elements in common, which can be applied in various scenarios like filtering data or validating conditions. - This snippet demonstrates how to utilize set operations effectively in Python for logical comparisons.
Output
Understanding set subset relationships in Python with the issubset method
Explanation
- The code creates two sets s1 containing elements {1,2,3,4,5} and s2 containing elements {3,4,5}
- The issubset() method checks if all elements of one set exist within another set
- s1.issubset(s2) returns False because s1 contains elements (1,2) that are not present in s2
- s2.issubset(s1) returns True because all elements of s2 (3,4,5) are contained within s1
- This demonstrates the directional nature of subset relationships in set theory operations
Output
Python set superset relationship checking with issuperset method
Explanation
- The code creates two sets s1 containing elements {1,2,3,4,5} and s2 containing elements {3,4,5}
- It uses the issuperset() method to check if one set contains all elements of another set
- The first print statement outputs True because s1 contains all elements of s2 (s1 is a superset of s2)
- The second print statement outputs False because s2 does not contain all elements of s1 (s2 is not a superset of s1)
- This demonstrates the directional nature of superset relationships in set theory operations
Output
This code demonstrates how to create a duplicate of a set in Python using the copy method.
Explanation
- A set
s1is initialized with five integer elements: 1, 2, 3, 4, and 5. - The
copy()method is called ons1to create a new sets2that is a duplicate ofs1. - Both sets
s1ands2are printed to the console, showing that they contain the same elements. - Modifications to
s2after this point will not affects1, demonstrating that they are independent copies.
Output
Frozenset
Frozen set is just an immutable version of a Python set object
Creating an immutable frozenset in Python for unique collection management
Explanation
- The code initializes a frozenset, which is an immutable version of a set in Python.
- The frozenset is created using a list of integers
[1, 2, 3], ensuring that the elements are unique and unordered. - Once created, the frozenset
fscannot be modified (no additions or removals of elements). - This is useful for scenarios where a constant collection of items is needed, providing both performance and safety against accidental changes.
- The frozenset can be used in situations where a set is required as a key in a dictionary or as an element in another set.
Output
Combining two frozensets to create a union in Python
Explanation
- The code defines two frozensets,
fs1andfs2, containing unique integer elements. - The
|operator is used to compute the union of the two frozensets, resulting in a new frozenset that contains all unique elements from both. - Frozensets are immutable, meaning their contents cannot be changed after creation, making them suitable for use as keys in dictionaries or elements in other sets.
- The resulting frozenset from the union will contain the elements
{1, 2, 3, 4, 5}.
Output
This code snippet demonstrates how to add an element to a set in Python.
Explanation
- The
add()method is used to insert a single element into a set. - In this case, the number
5is being added to the set referenced byfs1. - If
5is already present in the set, the set remains unchanged since sets do not allow duplicate values. - This operation modifies the set in place and does not return a new set.
Output
Understanding the functionality of read and write operations in Python code
Explanation
- The code comments clarify which operations are functional and which are not.
- It specifies that all read functions are operational, indicating successful data retrieval.
- Conversely, it notes that write operations are non-functional, suggesting limitations in data modification.
- This distinction is crucial for debugging and understanding the code's capabilities.
Creating a frozenset containing integers and another frozenset in Python
Explanation
- The code initializes a
frozenset, which is an immutable version of a set in Python. - It contains integers
1and2, as well as anotherfrozensetcontaining3and4. - Using
frozensetallows for the creation of a set that cannot be modified after its creation, ensuring data integrity. - This structure is useful for representing fixed collections of unique items, including nested sets.
- The outer
frozensetcan be used in contexts where a hashable collection is required, such as keys in a dictionary.
Output
Set Comprehension
This code snippet generates a set of integers from 1 to 10 using a set comprehension.
Explanation
- The code utilizes a set comprehension, which is a concise way to create sets in Python.
- The expression
range(1, 11)generates a sequence of numbers from 1 to 10 (inclusive of 1 and exclusive of 11). - Each integer
iin the specified range is added to the set, ensuring all elements are unique. - The resulting set will contain 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' : 'madhu' , 'age' : 30 , 'gender' : 'male' }
Characterstics:
- Mutable
- Indexing has no meaning
- keys can't be duplicated
- keys can't be mutable items
Create Dictionary
Demonstrating the creation and printing of various types of dictionaries in Python
Explanation
- Initializes and prints an empty dictionary to show basic dictionary structure.
- Creates and prints a 1D dictionary with string keys and values to illustrate simple key-value pairs.
- Demonstrates a dictionary with mixed key types, including a tuple and a string, showcasing Python's flexibility with keys.
- Constructs and prints a 2D dictionary that contains nested dictionaries, representing more complex data structures.
Output
Creating dictionaries from sequences of key-value pairs in Python
Explanation
- The
dict()function is used to create a dictionary from a list of tuples, where each tuple represents a key-value pair. - In the first instance,
d4is initialized with integer keys and values, resulting in{1: 1, 2: 2, 3: 3}. - In the second instance,
d4is redefined with a mix of string and integer keys, producing{'name': 'madhu', 'age': 32, 3: 3}. - The
print()function outputs the contents of the dictionary to the console, allowing verification of its structure. - This approach demonstrates the flexibility of dictionaries in Python, accommodating various data types as keys and values.
Output
Understanding how Python handles duplicate keys in dictionaries
Explanation
- A dictionary in Python cannot have duplicate keys; if a key is repeated, the last occurrence will overwrite the previous one.
- In this snippet, the key 'name' is defined twice with different values: 'madhu' and 'dadi'.
- When printed, the dictionary
d5will only show the last value assigned to the key 'name', which is 'dadi'. - The output of the print statement will be
{'name': 'dadi'}, demonstrating the overwriting behavior. - This behavior is consistent across all versions of Python, ensuring that each key in a dictionary remains unique.
Output
Demonstrating the use of mutable and immutable keys in Python dictionaries
Explanation
- The first dictionary
d6uses a string and a tuple as keys, showcasing that tuples can be used as dictionary keys since they are immutable. - The second dictionary
d6attempts to use a tuple as both a key and a value, illustrating that while tuples can serve as keys, they can also hold other tuples as values. - The output of both print statements will display the contents of the dictionaries, confirming the successful use of the tuple as a key.
- This code snippet highlights the importance of using immutable types (like tuples) for dictionary keys in Python.
Output
Accessing items
Accessing values in a Python dictionary using different methods
Explanation
- A dictionary named
my_dictis created with keys 'name' and 'age', storing corresponding values 'Jack' and 26. - The first
printstatement retrieves the value associated with the key 'age' directly using bracket notation, outputting 26. - The second
printstatement uses thegetmethod to access the value for 'age', which also returns 26, demonstrating an alternative way to retrieve values. - The last line attempts to access a nested key 'maths' within a dictionary
s, but it will raise an error ifsis not defined, indicating a potential issue in the code.
Output
Adding key-value pair
This code snippet demonstrates how to add and update dictionary entries in Python.
Explanation
- The code initializes or updates the 'gender' key in the dictionary
d4with the value 'male' and prints the updated dictionary. - It then adds a new key 'weight' with the value 51 to the same dictionary
d4and prints the result again. - The code accesses another dictionary
s, specifically the nested 'subjects' dictionary, and updates the 'ds' key with the value 75. - Finally, it prints the updated dictionary
sto show the changes made.
Output
Remove key-value pair
Understanding dictionary manipulation methods in Python for data management
Explanation
- The code demonstrates various methods to modify a Python dictionary, including
pop,popitem,del, andclear. - The
popmethod removes a specified key (in this case, the integer3) and returns its value, modifying the dictionary in place. - The
popitemmethod removes and returns the last inserted key-value pair from the dictionary, which is useful for stack-like behavior. - The
delstatement is used to delete a specific key (here, 'name') from the dictionary, effectively removing that entry. - The
clearmethod empties the entire dictionary, removing all key-value pairs, and is demonstrated by printing the dictionary after the operation.
Output
Editing key-value pair
This code updates the 'ds' subject score in a nested dictionary structure.
Explanation
- The code accesses a nested dictionary
swhich contains a keysubjects. - It assigns the value
50to the keydswithin thesubjectsdictionary. - The updated dictionary
sis returned or displayed, reflecting the new score for 'ds'. - This operation is useful for modifying specific entries in complex data structures.
Output
Dictionary Operations
- Membership
- Iteration
This code snippet checks for the presence of specific strings in a variable.
Explanation
- The first line prints the value of the variable
s. - The second line checks if the substring 'madhu' exists within
sand prints the result (True or False). - The third line checks for the substring 'name' in
s, but it notes that only keys from a dictionary can be checked, not values. - This snippet demonstrates basic string membership testing in Python.
Output
This code snippet iterates through a dictionary and prints its keys along with their corresponding values.
Explanation
- A dictionary
dis defined with keys 'name', 'gender', and 'age', each associated with respective values. - A
forloop is used to iterate over each key in the dictionaryd. - Inside the loop, the current key
iand its corresponding valued[i]are printed to the console. - The output will display each key-value pair on a new line, providing a clear view of the dictionary's contents.
Output
Dictionary Functions
This code snippet demonstrates various operations on a data structure in Python, including length, sorting, and finding minimum and maximum values.
Explanation
- The
len(d)function returns the number of elements in the data structured. - The
print(d)statement outputs the current state ofdto the console. - The
sorted(d, reverse=True)function sorts the elements ofdin descending order and prints the sorted list. - The
min(d)function finds and prints the minimum value ind. - The
max(d)function retrieves and prints the maximum value ind, determined by ASCII values ifdcontains strings.
Output
Displaying dictionary contents using items, keys, and values in Python
Explanation
- The code prints the entire dictionary
dto the console. d.items()returns a view object that displays a list of dictionary's key-value tuple pairs.d.keys()returns a view object that displays a list of all the keys in the dictionary.d.values()returns a view object that displays a list of all the values in the dictionary.- These methods are useful for iterating through the dictionary or for debugging purposes.
Output
Python dictionary update method merges key-value pairs from one dictionary into another
Explanation
- The code demonstrates how to merge two dictionaries using the update() method in Python
- Dictionary d1 initially contains keys 1, 3, and 4 with corresponding values 2, 4, and 5 respectively
- Dictionary d2 contains keys 4 and 6 with values 7 and 8 respectively
- When update() is called, it adds all key-value pairs from d2 to d1, overwriting existing keys (key 4 gets updated from value 5 to 7)
- The final output shows the merged dictionary with keys 1, 3, 4, and 6 having values 2, 4, 7, and 8 respectively
Output
Dictionary Comprehension
Creating a dictionary of numbers and their squares using dictionary comprehension
Explanation
- Generates a dictionary with keys from 1 to 10 and values as their respective squares
- Uses dictionary comprehension syntax {key_expression: value_expression for item in iterable}
- The range(1,11) creates numbers 1 through 10 (exclusive of 11)
- Each key-value pair follows the pattern where key equals the number and value equals the square of that number
- Produces a compact one-line solution for mapping numbers to their squared values
Output
Convert distance values from kilometers to miles using a dictionary comprehension in Python
Explanation
- The code initializes a dictionary called
distanceswith city names as keys and their corresponding distances in kilometers as values. - A dictionary comprehension is used to create a new dictionary where each distance value is multiplied by 0.62 to convert kilometers to miles.
- The
items()method retrieves key-value pairs from the original dictionary for iteration. - The resulting dictionary will contain the same city names as keys, but the values will now represent distances in miles.
- This approach is efficient and concise, allowing for quick transformations of dictionary data.
Output
Create a dictionary mapping days of the week to corresponding temperatures in Celsius
Explanation
- The code defines two lists:
days, containing the names of the days of the week, andtemp_C, containing temperature values in Celsius. - The
zipfunction pairs elements from both lists, creating tuples of day-temperature pairs. - A dictionary comprehension is used to iterate over these tuples, constructing a dictionary where each day is a key and its corresponding temperature is the value.
- The resulting dictionary provides an easy way to look up the temperature for each day of the week.
Output
Filtering a dictionary to retain only available products in stock
Explanation
- A dictionary named
productsis defined with items and their respective stock quantities. - A dictionary comprehension is used to iterate over the items in
products. - The comprehension includes a condition that checks if the stock value is greater than zero.
- Only items that meet this condition are included in the resulting dictionary.
- The final output is a new dictionary containing only the products that are currently in stock.
Output
Generate multiplication tables for numbers 2 to 4 using nested dictionary comprehension in Python.
Explanation
- The outer dictionary comprehension iterates over the range from 2 to 4, creating keys for each number.
- The inner dictionary comprehension generates multiplication results for each key by iterating over the range from 1 to 10.
- Each key in the outer dictionary corresponds to a number, while the inner dictionary contains the products of that number with values from 1 to 10.
- The final output is a nested dictionary where each number maps to its multiplication table.
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.
Transforming a list of tuples into a structured list of unique elements and their associated values
Explanation
- The code initializes a list of tuples,
test_list, containing pairs of integers. - It extracts the first element from each tuple to create a set of unique values, ensuring no duplicates.
- A new list,
result, is constructed where each unique value is paired with its corresponding second elements from the original tuples. - The final output is printed in two formats: a list of lists and a list of tuples, showcasing the structured data.
Output
###Q2: Multiply Adjacent elements (both side) and take sum of right and lest side multiplication result.
For eg.
Transforming a tuple into a new tuple based on adjacent element multiplication
Explanation
- A tuple
tis defined with five integer elements. - An empty list
Lis initialized to store the results of calculations. - The first element of
Lis computed by multiplying the first two elements of the tuplet. - A loop iterates through the tuple from the second element to the second-to-last element, calculating a new value for each position based on the product of the current element with its adjacent elements.
- The last element of
Lis added by multiplying the last two elements of the tuplet, and the final listLis converted to a tuple and printed.
Output
###Q3: Check is tuples are same or not?
Two tuples would be same if both tuples have same element at same index
This code compares two tuples to check if they are identical element-wise.
Explanation
- Two tuples,
t1andt2, are defined with integer values. - A boolean variable
flagis initialized toTrueto track if the tuples are the same. - A loop iterates through both tuples simultaneously using
zip(), comparing corresponding elements. - If any pair of elements is not equal,
flagis set toFalse, and the loop breaks. - Finally, a conditional statement prints whether the tuples are the same based on the value of
flag.
Output
###Q4: Count no of tuples, list and set from a list
Output:
Count occurrences of different data types in a mixed collection using Python
Explanation
- Initializes a list
Lcontaining various data types: sets, tuples, and lists. - Creates an
outputlist to keep track of the counts for lists, sets, and tuples. - Iterates through each element in
L, checking its type and incrementing the corresponding count inoutput. - Finally, prints the counts of lists, sets, and tuples, but mistakenly uses the same count for all types in the output format.
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
This Python code collects applicant details and filters candidates based on specific criteria.
Explanation
- Initializes an empty list to store student details and prompts the user for the number of applicants.
- Uses a loop to gather each applicant's name, higher education, primary skill, and year of graduation, storing this information as tuples in the list.
- Prompts the user for required qualifications, including skill, higher education, and year of graduation to filter candidates.
- Iterates through the collected applicants to check if any match the specified criteria, printing the matching applicant's details if found.
- If no candidates meet the requirements, it outputs a message indicating that no suitable candidates were found.
Output
Set
###Q1: Write a program to find set of common elements in three lists using sets.
This code finds the common elements across multiple lists using set operations in Python.
Explanation
- The code initializes three lists,
ar1,ar2, andar3, containing integer values. - Each list is converted into a set (
s1,s2,s3) to utilize set operations, which automatically handle duplicates and allow for efficient membership testing. - The intersection of the sets is computed using the
&operator, which identifies elements present in all three sets. - The result is converted back to a list and printed, displaying the common elements across the three original lists.
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:
Count the number of unique vowels in a given string using Python sets
Explanation
- A set of vowels is created, containing both lowercase and uppercase vowels for comprehensive matching.
- A set
sis initialized with unique characters from the provided string, which includes a mix of letters and spaces. - The intersection of the two sets (
sandvowels) is calculated to find common elements, which represent the unique vowels in the string. - The length of the intersection set is printed, indicating the number of unique vowels found in the input string.
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.
This code checks if a string contains exactly two unique characters.
Explanation
- The variable
sis initialized with the string "Blog". - The
set(s)function creates a set of unique characters from the string. - The
len()function checks the number of unique characters in the set. - If there are exactly two unique characters, it prints 'binary'; otherwise, it prints 'not binary'.
- This code can be used to determine if a string is binary in terms of character diversity.
Output
Q4: find union of n arrays.
Example 1:
Input:
Output:
This code snippet aggregates unique elements from a list of lists into a set.
Explanation
- A list of lists
Lis defined, containing multiple sublists with integers. - An empty set
sis initialized to store unique elements. - A for loop iterates through each sublist in
L, updating the setswith elements from each sublist using theupdate()method. - The
update()method adds only unique elements to the set, automatically handling duplicates. - Finally, the set
sis printed, displaying all unique integers from the original list of lists.
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:
This code snippet finds common elements between two sets in Python.
Explanation
- The code defines two sets,
lst1andlst2, containing unique integers. - A list comprehension is used to iterate through
lst1and check if each item is also present inlst2. - The result is a list of items that are common to both sets, effectively performing an intersection operation.
- Since sets do not allow duplicate values, the output will contain only unique common elements.
- This approach is efficient due to the average O(1) time complexity for membership tests in sets.
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:
This code identifies the key with the most unique values in a dictionary.
Explanation
- A dictionary named
test_dictis defined, containing keys associated with lists of integers. - The code initializes
max_valto track the maximum number of unique values andmax_keyto store the corresponding key. - It iterates through each key in the dictionary, converting the associated list to a set to count unique values.
- If the count of unique values exceeds the current
max_val, it updates bothmax_valandmax_key. - Finally, it prints the key that has the highest number of unique values.
Output
Q2: Replace words from Dictionary. Given String, replace it’s words from lookup dictionary.
Example 1:
Input:
Output:
Example 2:
Input:
Output:
This code replaces specific words in a string with predefined phrases using a dictionary.
Explanation
- A string
test_stris defined containing a sentence. - A dictionary
repl_dictmaps specific words to their replacement phrases. - The code splits the original string into words and iterates through each word.
- If a word matches a key in the dictionary, it appends the corresponding value to the result list; otherwise, it appends the original word.
- Finally, the modified words are joined back into a single string and printed.
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:
Transforming a list of mixed data types into a list of dictionaries with specified keys
Explanation
- Initializes a list
test_listcontaining mixed data types (strings and integers) and akey_listwith two keys. - Calculates the length of
test_listand initializes an empty listresto store the resulting dictionaries. - Iterates through
test_listin steps of 2, using the current index to access key-value pairs. - Appends a dictionary to
resfor each pair of elements, mapping them to the keys fromkey_list. - Finally, prints the list of dictionaries, which organizes the data in a structured format.
Output
Q4: Convert a list of Tuples into Dictionary.
Example 1:
Input:
Output:
Example 2:
Input:
Output:
Transforming a list of tuples into a dictionary with names as keys and values as lists
Explanation
- Initializes a list of tuples
L1containing names and associated integer values. - Creates an empty dictionary
dto store the transformed data. - Iterates over each tuple in
L1, using the first element as the key and the second element as a single-item list value in the dictionary. - Finally, prints the resulting dictionary, which maps names to their corresponding values in list format.
Output
Q5: Sort Dictionary key and values List.
Example 1:
Input:
Output:
Example 2:
Input:
Output:
Sorting a dictionary by keys and values in Python
Explanation
- A dictionary
dis defined with keys 'c', 'b', and 'a', each associated with a list of integers. - The code initializes an empty dictionary
resto store the sorted results. - It iterates over the sorted keys of the dictionary
d, printing each key and its corresponding list of values. - For each key, the associated list is sorted and stored in the
resdictionary under the same key. - Finally, the sorted dictionary
resis printed, showing the keys in sorted order with their values also sorted.
Output
Next in this series: Functions in Python: A Practical Guide With Examples →

