What Are Mutable and Immutable Types?: Objects of Built-In Type That Are Immutable Are
What Are Mutable and Immutable Types?: Objects of Built-In Type That Are Immutable Are
Mutable is a fancy way of saying that the internal state of the object is changed/mutated. So, the simplest
definition is: An object whose internal state can be changed is mutable. On the other hand, immutable doesn’t
allow any change in the object once it has been created.
Mutable Definition
Mutable is when something is changeable or has the ability to change. In Python, ‘mutable’ is the ability
of objects to change their values. These are often the objects that store a collection of data.
Immutable Definition
Immutable is the when no change is possible over time. In Python, if the value of an object cannot be
changed over time, then it is known as immutable. Once created, the value of these objects is permanent.
List of Mutable and Immutable objects
Objects of built-in type that are mutable are:
Lists
Sets
Dictionaries
User-Defined Classes (It purely depends upon the user to define the characteristics)
Objects of built-in type that are immutable are:
Numbers (Integer, Rational, Float, Decimal, Complex & Booleans)
Strings
Tuples
Frozen Sets
User-Defined Classes (It purely depends upon the user to define the characteristics)
Object mutability is one of the characteristics that makes Python a dynamically typed language. Though
Mutable and Immutable in Python is a very basic concept, it can at times be a little confusing due to the
intransitive nature of immutability.
%c character
%o octal integer
2. upper()method
Python string method upper() returns a copy of the string in which all case-based characters have been
uppercased.
Syntax
Following is the syntax for upper() method −
str.upper()
Parameters
NA
Return Value
This method returns a copy of the string in which all case-based characters have been uppercased.
Example
The following example shows the usage of upper() method.
str = "this is string example....wow!!!";
print "str.capitalize() : ", str.upper()
When we run above program, it produces following result −
str.capitalize() : THIS IS STRING EXAMPLE....WOW!!!
3. lower() Method
Python string method lower() returns a copy of the string in which all case-based characters have been
lowercased.
Syntax
Following is the syntax for lower() method −
str.lower()
Parameters
NA
Return Value
This method returns a copy of the string in which all case-based characters have been lowercased.
Example
The following example shows the usage of lower() method.
str = "THIS IS STRING EXAMPLE....WOW!!!";
print str.lower()
When we run above program, it produces following result –
this is string example....wow!!!
4. replace() method
Python string method replace() returns a copy of the string in which the occurrences of old have been
replaced with new, optionally restricting the number of replacements to max.
Syntax
Following is the syntax for replace() method −
str.replace(old, new[, max])
Parameters
old − This is old substring to be replaced.
new − This is new substring, which would replace old substring.
max − If this optional argument max is given, only the first count occurrences are replaced.
Return Value
This method returns a copy of the string with all occurrences of substring old replaced by new. If the
optional argument max is given, only the first count occurrences are replaced.
Example
The following example shows the usage of replace() method.
str = "this is string example....wow!!! this is really string"
print str.replace("is", "was")
print str.replace("is", "was", 3)
When we run above program, it produces following result −
thwas was string example....wow!!! thwas was really string
thwas was string example....wow!!! thwas is really string
5. find() method
Python string method find() determines if string str occurs in string, or in a substring of string if starting
index beg and ending index end are given.
Syntax
str.find(str, beg=0, end=len(string))
Parameters
str − This specifies the string to be searched.
beg − This is the starting index, by default its 0.
end − This is the ending index, by default its equal to the length of the string.
Return Value
Index if found and -1 otherwise.
Example
str1 = "this is string example....wow!!!";
str2 = "exam";
print str1.find(str2)
print str1.find(str2, 10)
print str1.find(str2, 40)
Result
15
15
-1
6. translate() method
Python string method translate() returns a copy of the string in which all characters have been translated
using table (constructed with the maketrans() function in the string module), optionally deleting all characters
found in the string deletechars.
Syntax
Following is the syntax for translate() method −
str.translate(table[, deletechars]);
Parameters
table − You can use the maketrans() helper function in the string module to create a translation table.
deletechars − The list of characters to be removed from the source string.
Return Value
This method returns a translated copy of the string.
Example
The following example shows the usage of translate() method. Under this every vowel in a string is
replaced by its vowel position −
from string import maketrans # Required to call maketrans function.
intab = "aeiou"
outtab = "12345"
trantab = maketrans(intab, outtab)
str = "this is string example....wow!!!";
print str.translate(trantab)
When we run above program, it produces following result −
th3s 3s str3ng 2x1mpl2....w4w!!!
Following is the example to delete 'x' and 'm' characters from the string −
from string import maketrans # Required to call maketrans function.
intab = "aeiou"
outtab = "12345"
trantab = maketrans(intab, outtab)
str = "this is string example....wow!!!";
print str.translate(trantab, 'xm')
This will produce following result −
th3s 3s str3ng 21pl2....w4w!!!
4 Lists consume more memory Tuple consume less memory as compared to the list
There are numerous Python template engine implementations that range from weekend hacks to
actively developed mature libraries. These template engines are listed alphabetically:
Chameleon is an HTML and XML template engine that supports both Python 2 and 3.
Cheetah
Diazo
evoque
Genshi
Juno
Myghty
pyratemp
pystache
Python has a set of built-in methods that you can use on lists
append() : Adds an element at the end of the list
clear() : Removes all the elements from the list
copy() : Returns a copy of the list
count() : Returns the number of elements with the specified value
extend() : Add the elements of a list (or any iterable), to the end of the current list
index() : Returns the index of the first element with the specified value
insert() : Adds an element at the specified position
pop() : Removes the element at the specified position
remove() : Removes the first item with the specified value
reverse() : Reverses the order of the list
sort() : Sorts the list
#define list
lst = []
for n in range(num):
#append element in list/array
numbers = int(input("Enter the array of %d element :- " %n))
lst.append(numbers)
i=0
flag = False
for i in range(len(lst)):
if lst[i] == x:
flag = True
break
if flag == 1:
print('{} was found at index {}.'.format(x, i))
else:
print('{} was not found.'.format(x))
output:
After executing the program, the output will be:
Enter size of list :- 6
Enter the array of 0 element :- 25
Enter the array of 1 element :- 50
Enter the array of 2 element :- 100
Enter the array of 3 element :- 200
Enter the array of 4 element :- 250
Enter the array of 5 element :- 650
Enter number to search in list :- 200
200 was found at index 3.
11 a What is Dictionary? Explain Python dictionaries in detail discussing its operations and methods.
Dictionary operations
Dictionaries are Python’s implementation of a data structure that is more generally known as an
associative array. A dictionary consists of a collection of key-value pairs. Each key-value pair maps the
key to its associated value.
You can define a dictionary by enclosing a comma-separated list of key-value pairs in curly
braces ({}). A colon (:) separates each key from its associated value:
1. Definition operations
These operations allow us to define or create a dictionary.
{}
2. Mutable operations
These operations allow us to work with dictionaries, but altering or modifying their previous definition.
[]
Adds a new pair of key and value to the dictionary, but in case that the key already exists in the
dictionary, we can update the value.
y = {}
y['one'] = 1
y['two'] = 2
print(y)
Output:
{'one': 1, 'two': 2}
y['two'] = 'dos'
print(y)
Output:
{'one': 1, 'two': 'dos'}
As I told you before, the key value should be an immutable data type, for that reason if you try to define a
dictionary with a mutable data type, Python will raise a TypeError: unhashable type exception.
del
Del statement can be used to remove an entry (key-value pair) from a dictionary.
y = {'one': 1, 'two': 2}
print(y)
Output:
{'one': 1, 'two': 2}
del y['two']
print(y)
Output:
{'one': 1}
update
This method updates a first dictionary with all the key-value pairs of a second dictionary. Keys
that are common to both dictionaries, the values from the second dictionary override those of the first.
x = {'one': 0, 'two': 2}
y = {'one': 1, 'three': 3}
x.update(y)
print(x)
Output:
{'one': 1, 'two': 2, 'three': 3}
3. Immutable operations
These operations allow us to work with dictionaries without altering or modifying their previous
definition.
len
Returns the number of entries (key-value pairs) in a dictionary.
x = {'one': 0, 'two': 2}
print(len(x))
Output:
2
keys
This method allows you to get all the keys in the dictionary. It is often used in a “for loop” to
iterate over the content of a dictionary.
x = {'one': 1, 'two': 2}
print(x.keys())
Output:
dict_keys(['one', 'two'])
values
This method allows you to obtain all the values stored in a dictionary.
x = {'one': 1, 'two': 2}
print(x.values())
Output:
dict_values([1, 2])
items
Returns all the keys and their associated values as a sequence of tuples.
x = {'one': 1, 'two': 2}
print(x.items())
Output:
dict_items([('one', 1), ('two', 2)])
in
Attempting to access a key that is not in a dictionary will raise an exception. To handle this
exception, you can use the in method that test whether a key exists in a dictionary, returns True if a
dictionary has a value stored under the given key and False otherwise.
y = {'one': 1, 'two': 2}
del y['three']
Output:
KeyError: 'three'y = {'one': 1, 'two': 2}
if 'three' in y:
del y['three']
print(y)
Output:
{'one': 1, 'two': 2}
get
Returns the value associated with a key if the dictionary contains that key, in case that the
dictionary does not contain the key, you can specified a second optional argument to return a default
value, if the argument is not included get method will return None.
y = {'one': 1, 'two': 2}
print(y.get('one'))
print(y.get('three'))
print(y.get('three', 'The key does not exist.'))
Output:
1 None The key does not exist.
setdefault
This method is similar to get method, it returns the value associated with a key if the dictionary
contains that key, but in case that the dictionary does not contain the key, this method will create a new
element in the dictionary (key-value pair), where the first argument in this method is the key, and the
second argument is the value. The second argument is optional, but if this is not included, the value will
be None.
y = {'one': 1, 'two': 2}
print(y.setdefault('three', '3'))
print(y.setdefault('two', 'dos'))
print(y)
Output:
32{'one': 1, 'two': 2, 'three': '3'}
These are some of the most common and important operations related to Python dictionaries, and
this is one of the main reasons to know them in detail.
I invite you to comment on any detail that has not been mentioned. I am sure that your
contribution will be very valuable.
11 b Describe the need for catching exceptions using try and except statements.
In Python, exceptions can be handled using a try statement.
The critical operation which can raise an exception is placed inside the try clause. The code that handles the
exceptions is written in the except clause.
We can thus choose what operations to perform once we have caught the exception. Here is a simple
example.
Output:
The entry is a
Oops! <class 'ValueError'> occurred.
Next entry.
The entry is 0
Oops! <class 'ZeroDivisionError'> occured.
Next entry.
The entry is 2
The reciprocal of 2 is 0.5
In this program, we loop through the values of the randomList list. As previously mentioned, the portion that can
cause an exception is placed inside the try block.
If no exception occurs, the except block is skipped and normal flow continues(for last value). But if any
exception occurs, it is caught by the except block (first and second values).
Here, we print the name of the exception using the exc_info() function inside sys module. We can see that a
causes ValueError and 0 causes ZeroDivisionError.
Since every exception in Python inherits from the base Exception class, we can also perform the above task in the
following way:
We can use a tuple of values to specify multiple exceptions in an except clause. Here is an example pseudo
code.
try:
# do something
pass
except ValueError:
# handle ValueError exception
pass
except (TypeError, ZeroDivisionError):
# handle multiple exceptions
# TypeError and ZeroDivisionError
pass
except:
# handle all other exceptions
pass
We can optionally pass values to the exception to clarify why that exception was raised.
>>> raise KeyboardInterrupt
Traceback (most recent call last):
...
KeyboardInterrupt
>>> raise MemoryError("This is an argument")
Traceback (most recent call last):
...
MemoryError: This is an argument
>>> try:
... a = int(input("Enter a positive integer: "))
... if a <= 0:
... raise ValueError("That is not a positive number!")
... except ValueError as ve:
... print(ve)
...
Enter a positive integer: -2
That is not a positive number!
Python try with else clause
In some situations, you might want to run a certain block of code if the code block inside try ran without any
errors. For these cases, you can use the optional else keyword with the try statement.
Note: Exceptions in the else clause are not handled by the preceding except clauses.