Python Module2
Python Module2
A shallow copy creates a new list but copies references to the nested
lists. Modifications to nested elements affect both the original and the
Similarities between Lists and Strings: copied list.
1. Ordered Collections: Both are ordered sequences of elements. Difference Between Deep and Shallow Copy:
2. Indexing and Slicing: Both support indexing and slicing to access
Aspect Shallow Copy Deep Copy
or modify elements.
3. Iteration: Both can be iterated over in loops. Nested Copies references to nested Recursively copies nested
Objects objects (e.g., sublists) objects (new copies)
Differences between Lists and Strings:
Changes to mutable objects
1. Element Types: Lists can contain any type of data (integers, Changes to nested objects
Independence in nested lists affect both
strings, etc.), while strings only contain characters. only affect the deep copy
copies
2. Mutability: Lists are mutable (can be changed), whereas strings
Faster (shallow copy of Slower (due to recursive
are immutable (cannot be modified directly). Performance
references) copying of all objects)
3. Concatenation: Both can be concatenated using the + operator, but
lists combine as lists, and strings combine as text. Shallow Copy with Nested List:
4. Methods: Lists have methods like append() and pop(), while If a list with a nested list undergoes a shallow copy, the nested list is
strings have methods like upper() and split(). shared between the original and copy. Changes to the nested list will
affect both.
5. Use Cases: Lists are used for collections of elements, while
strings are used for text manipulation. Example:
original_list = [1, [2, 3], 4]
2 )What is deep copy of a list? How is it different from shallow copy? What happens shallow_copy_list = original_list.copy()
when a list having a nested list undergoes shallow copy? shallow_copy_list[1][0] = 99
print(original_list) # [1, [99, 3], 4]
Deep Copy:
A deep copy creates a completely independent copy of the list, including
all nested lists. Modifications to nested elements in the copy do not
affect the original list.
Shallow Copy: 3 )Analyse the statement “Tuples are immutable”.
he statement "Tuples are immutable" means that once a tuple is created,
its elements cannot be changed, added, or removed. You cannot modify
individual items or perform operations like append() or del() on a tuple. Tuple Unpacking is when elements of a tuple are assigned to separate
However, if a tuple contains mutable objects (e.g., lists), those objects variables.
can still be modified.
Example:
Tuples are hashable due to their immutability, which allows them to be
my_tuple = (1, "Hello", 3.14)
used as keys in dictionaries or elements in sets. This immutability
ensures data safety, consistency, and efficiency, as tuples cannot be a, b, c = my_tuple
accidentally altered.
6) When are dictionaries more useful than lists?
my_dict = { (1, 2, 3): "value" } # tuple is hashable, can be used as a key
1. Key-Value Pairs: To store data with unique keys.
my_dict = { [1, 2, 3]: "value" } # This will raise: TypeError: unhashable type
my_dict = {"name": "Alice", "age": 25}
2. Efficient Lookup: Fast access by key with O(1) time complexity.
4 )What advantages do tuples have over lists?
3. Unique Keys: Ensuring no duplicate keys.
Tuples have several advantages over lists:
4. Complex Data Mapping: When elements are related, like mapping
1. Immutability: Tuples cannot be modified, making them safer for names to contact info.
fixed data.
5. Specific Updates: Adding, removing, or modifying elements using
2. Performance: Tuples are faster and more memory-efficient due to a key rather than an index.
their fixed size.
In short, dictionaries are better for key-based lookups and mapping data
3. Hashability: Tuples can be used as dictionary keys or set efficiently
elements, unlike lists.
7 ) Can a dictionary have a list as a key or a value? Can it have any tuple as a key?
4. Memory Efficiency: Tuples use less memory than lists due to their
Can a dictionary have a list as a key?
fixed size.
No, dictionaries cannot have lists as keys because lists are mutable. In
Overall, tuples are better for storing constant data, while lists are more
Python, dictionary keys must be hashable, and mutable objects like lists
suitable for dynamic collections.
are not hashable.
5 )Explain tuple packing and unpacking in Python with relevant example(s).
my_dict = {[1, 2, 3]: "value"} # This will raise: TypeError: unhashable type:
Tuple Packing is when multiple values are grouped into a single tuple. 'list'
Example:
python Can a dictionary have a list as a value?
Copy code Yes, dictionaries can have lists as values because values can be
mutable. Lists can be assigned as values to keys without issue.
my_tuple = (1, "Hello", 3.14)
my_dict = {"key1": [1, 2, 3], "key2": [4, 5, 6]} clone_list[0] = 99 # Modifying clone_list does not affect original_list
print(my_dict) # Output: {'key1': [1, 2, 3], 'key2': [4, 5, 6]} print(original_list) # Output: [1, 2, 3]
Can a dictionary have any tuple as a key? print(clone_list) # Output: [99, 2, 3]
Yes, dictionaries can have tuples as keys, but only if the tuple is
immutable. If the tuple contains mutable elements (like lists), it will not
9 )Explain how the ‘split’ and ‘join’ methods work in Python strings.
be hashable and cannot be used as a dictionary key.
split() Method:
my_dict = {(1, 2): "value"} # Valid because the tuple is immutable
The split() method is used to break a string into a list of substrings
my_dict = {(1, [2, 3]): "value"} # Invalid because the tuple contains a list,
based on a delimiter.
which
• Syntax: string.split(separator, maxsplit)
8 )Differentiate between aliasing and cloning of lists with relevant examples.
o separator: The delimiter where the string will be split
Aliasing:
(default is any whitespace).
• Definition: Aliasing occurs when two variables refer to the same
o maxsplit: The maximum number of splits to perform
list in memory. Changes made to one list will affect the other
(optional).
because they both point to the same object.
• Example:
• Example:
text = "Hello, World, Python"
original_list = [1, 2, 3]
result = text.split(", ") # Split at comma and space
alias_list = original_list # Both variables refer to the same list
print(result) # Output: ['Hello', 'World', 'Python']
alias_list[0] = 99 # Modifying alias_list also modifies original_list
Without a separator (splits by whitespace by default):
print(original_list) # Output: [99, 2, 3]
text = "Hello World Python"
print(alias_list) # Output: [99, 2, 3]
result = text.split() # Split by any whitespace
Cloning:
print(result) # Output: ['Hello', 'World', 'Python']
• Definition: Cloning creates a new, independent copy of the list, so
changes made to the clone do not affect the original list.
• Example:
original_list = [1, 2, 3] join() Method:
clone_list = original_list.copy() # Creates a new copy of the list The join() method is used to join a list of strings into a single string,
using a specified delimiter.
• Syntax: separator.join(iterable) Example:
o separator: The string that will be used to join the elements. text = "Hello, World!"
o iterable: The list or tuple of strings to be joined. result = text.index("World") # Returns index of "World"
• Example: print(result) # Output: 7
words = ['Hello', 'World', 'Python'] # Raises an error if substring is not found
result = ", ".join(words) # Join with comma and space result_not_found = text.index("Python")
print(result) # Output: "Hello, World, Python" except ValueError as e:
print(e) # Output: substring not found
10) Explain with example(s) the difference between ‘find’ and ‘index’ methods of Summary:
Python strings.
• find(): Returns -1 if the substring is not found.
Both find() and index() are used to search for a substring within a string,
• index(): Raises a ValueError if the substring is not found.
but they differ in behavior when the substring is not found.
find() Method:
11) . Explain with example(s) the difference between append and extend method of a
• Returns: The index of the first occurrence of the substring. If the
list.
substring is not found, it returns -1.
Both append() and extend() add elements to a list, but they do so in
• Does not raise an error if the substring is not found.
different ways.
Example:
append() Method:
text = "Hello, World!"
• Adds a single element to the end of the list.
result = text.find("World") # Returns index of "World"
• The element can be any object, including a list, which will be
print(result) # Output: 7
added as a single element (nested).
result_not_found = text.find("Python") # Returns -1 if not found
Example:
print(result_not_found) # Output: -1
my_list = [1, 2, 3]
index() Method:
my_list.append(4) # Adds 4 as a single element
• Returns: The index of the first occurrence of the substring. If the
substring is not found, it raises a ValueError. print(my_list) # Output: [1, 2, 3, 4]
sliced_dict = my_dict[0:2] # Error: TypeError: unhashable type: 'slice' • Syntax: Specified using / in the function definition.
14.) Explain with a suitable example the use of lambda expression. Example:
A lambda expression is a small anonymous function defined using the def func(a, b, /):
lambda keyword. It can take any number of arguments but can only have
print(a, b)
one expression.
func(1, 2) # Valid
Syntax:
func(a=1, b=2) # Error: TypeError: func() got some positional-only
lambda arguments: expression
arguments
# Lambda function to add two numbers
2. Positional or Keyword Parameters:
add = lambda x, y: x + y
• Definition: These parameters can be passed either by position or
result = add(3, 5) by keyword.
Summary:
• Unpacking: Passing a list/tuple to a function and expanding it into
individual arguments (*args).
• Packing: Accepting a variable number of positional arguments in a
functio