Hey everyone, I'm back! After a brief hiatus due to exams, I'm thrilled to announce that I'm resuming my blog writing journey. The exams went well, and now I'm eager to dive back into creating content. Get ready for some exciting article posts coming your way soon. Let's continue this walk together!
.get(_,_)
.get()
method is primarily used with dictionaries to retrieve the value associated with a specified key. It provides a way to safely access a value from a dictionary without raising a KeyError
if the key is not found. The .get()
method takes two parameters:
Key: The key whose value is to be retrieved.
Default (Optional): The default value to be returned if the key is not found in the dictionary.
Here's the syntax:
value = dictionary.get(key, default)
key
: The key for which you want to retrieve the associated value.default
: (Optional) The value to return if the key is not found. If not specified,None
is returned by default.
Here's an example to illustrate its usage:
my_dict = {'a': 1, 'b': 2, 'c': 3}
# Using .get() to retrieve values
value_a = my_dict.get('a')
print(value_a) # Output: 1
value_d = my_dict.get('d')
print(value_d) # Output: None
# Specifying a default value
value_d_default = my_dict.get('d', 'Key not found')
print(value_d_default) # Output: Key not found
In this example:
value_a
gets assigned the value associated with the key'a'
, which is1
.value_d
attempts to retrieve the value associated with the key'd'
, which does not exist in the dictionary, so it returnsNone
.value_d_default
specifies a default value'Key not found'
to be returned if the key'd'
is not found in the dictionary. Since'd'
is not in the dictionary, the default value is returned.
What happens to a dictionary when the same key is assigned two different values at the time of initialization?
D = {'a': 1, 'b': 2, 'c': 3, 'a': 4, 'a': 5}
print(D) # op : {'a': 5, 'b': 2, 'c': 3}
So, it makes a lot of sense to retain the last update to the key 'a' .
Shallow and Deep Copy
Consider the following code:
mat1 = [[1, 2], [3, 4]]
mat2 = mat13mat2.append([5, 6])
print(mat1)
print(mat2)
print(mat1 is mat2)
We already know what will happen here. Lists are mutable. mat2
is just an alias for mat1
and both point to the same object. Modifying any one of them will modify both. We also saw three different methods to copy lists so that modifying one doesn't modify the other. Let us try one of them:
mat2 = mat1.copy()
mat2.append([5, 6])
print(mat1)
print(mat2)
print(mat1 is mat2)
No problems so far. But try this:
mat1 = [[1, 2], [3, 4]]
mat2 = mat1.copy()
mat2[0][0] = 100
print(mat1)
print(mat2)
This is the output we get:
[[100, 2], [3, 4]]
[[100, 2], [3, 4]]
What is happening here? mat1
has also changed! Wasn't copy
supposed to get rid of this difficulty? We have a mutable object inside another mutable object. In such a casecopy
just does a shallow copy; only a new outer-list object is produced. This means that the inner lists inmat1
andmat2
are still the same objects:
print(mat1[0] is mat2[0])
print(mat1[1] is mat2[1])
Both lines print True
. In order to make a copy where both the inner and outer lists are new objects, we turn to deepcopy:
1from copy import deepcopy2mat1 = [[1, 2], [3, 4]]3mat2 = deepcopy(mat1)4mat2[0][0] = 1005print(mat1)6print(mat2)
This gives the output:
[[1, 2], [3, 4]]
[[100, 2], [3, 4]]
Finally we have two completely different objects:
from copy import deepcopy
mat1 = [[1, 2], [3, 4]]
mat2 = deepcopy(mat1)
print(mat1 is not mat2)
print(mat1[0] is not mat2[0])
print(mat1[1] is not mat2[1])
All three print True
! deepcopy
is a function from the library copy
. We won't enter into how it works. Suffice to say that when using nested lists or any collection of mutable objects, use deepcopy
if you wish to make a clean copy.
Immutability of strings and tuples
Immutability of Strings:
Strings are sequences of characters, enclosed within single quotes (' '), double quotes (" "), or triple quotes (''' ''' or """ """).
Once a string is created, its contents cannot be changed. Attempting to modify a string directly will result in an error.
However, you can create new strings by concatenating existing strings or using string manipulation methods. These operations do not modify the original strings but instead create new ones.
Example:
s = "hello"
# This will raise an error because strings are immutable
# s[0] = 'H'
# Instead, you can create a new string by concatenating
new_s = 'H' + s[1:]
print(new_s) # Output: "Hello"
Immutability of Tuples:
Tuples are ordered collections of items, enclosed within parentheses ().
Similar to strings, once a tuple is created, its elements cannot be modified. Attempting to change a tuple's elements directly will result in an error.
However, you can create new tuples by concatenating or combining existing tuples, but you cannot modify the original tuples.
Example:
t = (1, 2, 3)
# This will raise an error because tuples are immutable
# t[0] = 4
# Instead, you can create a new tuple by concatenating
new_t = (4,) + t[1:]
print(new_t) # Output: (4, 2, 3)
In essence, immutability ensures that once strings and tuples are defined, their values remain fixed throughout the program execution. This characteristic makes them suitable for scenarios where data integrity and consistency are important.
Initializing a set and the potential confusion with an empty dictionary
S = set()
S = { }
S = {1, 2, 3}
S = set([1, 2, 3, 4, 3, 2, 1])
{ } is the empty dictionary. Never mistake this for a set. Of course, notationally, we are referring to the Pythonic set and not the mathematical set here, though both have a lot in common.
so, here are some extra things I go to know about the previous topics after solving some questions and problems .. please stay updated I may add more info to this blog .. stay happy and happy learnings.
why to use another list while working with another list
l=[2,2,3,2,4,5,6,7,8,9]
for i in l:
if i==2:
l.remove(i)
else:
pass
print(l)
#{2, 3, 4, 5, 6, 7, 8, 9} : why 2 after 3 is not removed?
In Python, it's generally not a good idea to modify a list while iterating over it using a for
loop because it can lead to unexpected behavior. When you remove an element from a list while iterating over it, you're changing the size of the list, and this can mess up the iteration process.
In our code, when we remove an element (such as 2
) from the list l
using l.remove(i)
, it shifts the position of the subsequent elements in the list. This affects the iteration process, causing the loop to skip some elements. Specifically, the second 2
after 3
is not removed because it has shifted to a different position in the list due to the removal of the first 2
.
A safer approach to achieve what you want is to create a new list containing the elements you want to keep, rather than modifying the original list. You can use list comprehension for this purpose. Here's the corrected version of your code:
l = [2, 2, 3, 2, 4, 5, 6, 7, 8, 9]
l = [i for i in l if i != 2]
Join method of lists
The join()
method in Python is used to concatenate the elements of a list into a single string. It takes all elements of the list and joins them together using a specified separator string.
Here's the syntax of the join()
method:
separator_string.join(iterable)
separator_string
: This is the string that will be used as a separator between the elements of the list when they are joined together.iterable
: This is the list (or any iterable) whose elements you want to join together into a single string.
Here's an example of how to use the join()
method on a list:
codemy_list = ["apple", "banana", "cherry"]
result = ", ".join(my_list)
print(result)
This will output:
apple, banana, cherry
In this example, the join()
method concatenates the elements of the my_list
with a comma and a space (", "
) as the separator between each element. The resulting string is then assigned to the variable result
.
example:
def link(string):
l=string.split(".")
return( "<{0} class='{1}'></{0}> ".format(l[0],(" ").join(l[1:])))
print(link("p.container.row.colmd8"))
#op : <p class='container row colmd8'></p>