Module-2 Python Updated
Module-2 Python Updated
CSE 205
Programming in Python
Amity University Jharkhand, Ranchi
•Mutable Data Type – A mutable data type is those whose values can be
changed.
• Example: List, Dictionaries, and Set
•Immutable Data Type – An immutable data type is one in which the values
can’t be changed or altered.
• Example: String and Tuples
Amity University Jharkhand, Ranchi
Suppose we have a string called s and we want to change the character at index 4 of s to
'X'. It is tempting to try s[4]='X', but that unfortunately will not work. Python strings are
immutable, which means we can’t modify any part of them.
s="Testing"
print(s[:4] + 'X' + s[5:]);
Looping
Very often we will want to scan through a string one character at a time. A for loop
like the one below can be used to do that.
s="Testing"
for i in range(len(s)):
print (s[i])
In the range statement we have len(s) that returns how long s is.
Amity University Jharkhand, Ranchi
String methods
Strings come with a ton of methods, functions that return information about the
string or return a new string that is a modified version of the original.
Amity University Jharkhand, Ranchi
Amity University Jharkhand, Ranchi
String manipulation is very useful and very widely used in every language.
Often, programmers are required to break down strings and examine them
closely.
For example, a password strength checker would have to strip a string down and
examine them closely to see if it contains letters, numbers and/or symbols.
Amity University Jharkhand, Ranchi
The most basic way to manipulate strings is through the methods that are built into
Python.
Amity University Jharkhand, Ranchi
String Methods (String Manipulation)
We can perform:
String Checks:
- Find the length of a string
- Find out if a string is all in uppercase
- find out if a string is all in lowercase
- find out if a string’s words all start with capitals letters
- Check whether a string is alphanumeric(contains both letters and numbers)
- Check whether a string contains only numbers
- Check whether a string contains only letters
- Check whether a string only contains spaces
- Find the location of a character in a string
- Count how many times a character appears in a string String Formatting Methods:
- Turn a string upper case
- Turn a string lower case
String to Lists Conversions: - Capitalize a string (make first letter capital)
- Capitalize each word in a string
- Split a string into a number of items on a list
- Swap the case of each letter in a string around
- Add spaces in either side of a string.
We know from before that the ‘+’ operator is used to add numeric data types
together.
This operator has a different function when it deals with strings. The ‘+’ sign
simply joins together two or more string.
full_name_no_space = firstname + surname
Example:
Full_name = firstname + “ ” + surname
Amity University Jharkhand, Ranchi
Find the length of a string
The len function:
This helps us find the length
of a string (how many
characters it has – including
spaces)
Or
Amity University Jharkhand, Ranchi
Amity University Jharkhand, Ranchi
Look at each character of string in turn
Amity University Jharkhand, Ranchi
Or
Amity University Jharkhand, Ranchi
Or
Amity University Jharkhand, Ranchi
Or
Amity University Jharkhand, Ranchi
Or
Amity University Jharkhand, Ranchi
Or
Amity University Jharkhand, Ranchi
For digits:
{0:2d} {1:3d} {2:4d}
means, in the first
column (0) allow for 2
digits, in the second
column (1) allow for 3
digits etc.
For strings:
{0:10} means, in the first
column, allow for 10
characters.
Amity University Jharkhand, Ranchi
Converting between
Strings and Lists
Amity University Jharkhand, Ranchi
Amity University Jharkhand, Ranchi
Or
Amity University Jharkhand, Ranchi
Find the location of a character in a string
Or
Amity University Jharkhand, Ranchi
Write a program that asks the user to enter a string. The program should then print
the following:
(a) The total number of characters in the string
(b) The string repeated 10 times
(c) The first character of the string (remember that string indices start at 0)
(d) The first three characters of the string
(e) The last three characters of the string
(f) The string backwards
(g) The seventh character of the string if the string is long enough and a message
otherwise
(h) The string with its first and last characters removed
(i) The string in all caps
(j) The string with every a replaced with an e
(k) The string with every letter replaced by a space
Amity University Jharkhand, Ranchi
Lists
Python Lists are just like dynamically sized arrays, declared in other languages
(vector in C++ and ArrayList in Java). In simple language, a list is a collection of
things, enclosed in [ ] and separated by commas.
The list is a sequence data type which is used to store the collection of
data. Tuples and String are other types of sequence data types.
# Creation of List
# Creating a List
List = []
print("Blank List: ") Output:
print(List)
Blank List:
# Creating a List of numbers []
List = [10, 20, 14]
print("\nList of numbers: ") List of numbers:
print(List) [10, 20, 14]
Similarities to strings
Amity University Jharkhand, Ranchi
L = [1,2,3]
for i in range(len(L)):
print(L[i])
for item in L:
print(item)
Output:
Amity University Jharkhand, Ranchi
Built-in functions
Amity University Jharkhand, Ranchi
Output:
Amity University Jharkhand, Ranchi
List methods
Amity University Jharkhand, Ranchi
Amity University Jharkhand, Ranchi
Write a program that asks the user to enter a list of integers. Do the
following:
(a) Print the total number of items in the list.
(b) Print the last item in the list.
(c) Print the list in reverse order.
(d) Print Yes if the list contains a 5 and No otherwise.
(e) Print the number of fives in the list.
(f) Remove the first and last items from the list, sort the remaining
items, and print the
(g) Print how many integers in the list are less than 5.
Amity University Jharkhand, Ranchi
Join
Amity University Jharkhand, Ranchi
Amity University Jharkhand, Ranchi
Amity University Jharkhand, Ranchi
Tuples in Python
Python Tuple is a collection of objects separated by commas. In some ways, a
tuple is similar to a Python list in terms of indexing, nested objects, and repetition
but the main difference between both is Python tuple is immutable, unlike the
Python list which is mutable.
Output:
(1, 2, 4, ‘testing)
variable called values which holds a tuple that consists of either int or str, the
‘…’ means that the tuple will hold more than one int or str.
In case your generating a tuple with a single element, make sure to add a
comma after the element. Let us see an example of the same.
Amity University Jharkhand, Ranchi
mytuple = (1, 2, 3, 4, 5)
# adding an element
mytuple[1] = 100
print(mytuple)
Amity University Jharkhand, Ranchi
Output:
Value in Var[0] = hello
Value in Var[1] = for
Value in Var[2] = testing
Amity University Jharkhand, Ranchi
myList = [1, 2, 3, 4, 5]
# NORMAL INDEXING
print(myList[0])
print(myList[1])
print(myList[2])
# NEGATIVE INDEXING (STARTS FROM THE LAST ELEMENT IN THE LIST)
print(myList[-1])
print(myList[-2])
print(myList[-3])
print(myList[-3:])
1
2
3
5
4
3
[3, 4, 5]
Amity University Jharkhand, Ranchi
Output:
(0, 1, 2, 3, 'python', ‘Testing')
Amity University Jharkhand, Ranchi
Nesting of Python Tuples
(0, 1, 2)
('p', 'y', 't', 'h', 'o', 'n')
Amity University Jharkhand, Ranchi
t1=(3,4,2,1,5,6,7)
print(t1[2:5])
t2=list(t1)
t2[3]=99
t2.sort()
t3=tuple(t2)
print(t3)
Amity University Jharkhand, Ranchi
Dictionaries
A dictionary is a more general version of a list. In Python, a dictionary is mapping
between a set of indices (keys) and a set of values.The items in a dictionary are
key-value pairs
Creating dictionaries Here is a simple dictionary:
d = {'A':100, 'B':200}
To declare a dictionary we enclose it in curly braces, {}. Each entry consists of a pair
separated by a colon. The first part of the pair is called the key and the second is the
value. The key acts like an index. So in the first pair, 'A':100, the key is 'A', the value is
100, and d['A'] gives 100. Keys are often strings, but they can be integers, floats, and
many other things as well. You can mix different types of keys in the same dictionary
and different types of values, too.
Amity University Jharkhand, Ranchi
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = thisdict["model"]
print(x)
x = thisdict.keys()
print(x)
Amity University Jharkhand, Ranchi
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.copy()
print(x)
car.clear()
Print(car)
Output:
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
{}
Amity University Jharkhand, Ranchi
Nested Dictionary
Output:
{'child1': {'name': 'Emil', 'year': 2004}, 'child2':
{'name': 'Tobias', 'year': 2007}, 'child3':
{'name': 'Linus', 'year': 2011}}
Amity University Jharkhand, Ranchi
Output:
{'child1': {'name': 'Emil', 'year':
2004}, 'child2': {'name': 'Tobias',
'year': 2007}, 'child3': {'name':
'Linus', 'year': 2011}}
Amity University Jharkhand, Ranchi
The list of the keys is a view of the dictionary, meaning that any
changes done to the dictionary will be reflected in the keys list.
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.keys() Output
Change Values
You can change the value of a specific item by referring to its key name:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["year"] = 2018
print(thisdict)
Update Dictionary
The update() method will update the dictionary with the items from the given argument.The argument must be a
dictionary, or an iterable object with key:value pairs.
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.update({"year": 2020})
print(thisdict)
Adding Items
Adding an item to the dictionary is done by using a new index key and
assigning a value to it:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["color"] = "red"
print(thisdict)
Removing Items
There are several methods to remove items from a dictionary:
The pop() method removes the item with the specified key name:
thisdict = { thisdict = {
"brand": "Ford",
"model": "Mustang",
"brand": "Ford",
"year": 1964 "model": "Mustang",
}
thisdict.pop("model") "year": 1964
print(thisdict) }
thisdict.popitem()
print(thisdict)
{'brand': 'Ford', 'year': 1964}
Amity University Jharkhand, Ranchi
Set
A Set in Python programming is an unordered collection data type that is
iterable, mutable and has no duplicate elements.
Set are represented by { } (values enclosed in curly braces)
The major advantage of using a set, as opposed to a list, is that it has a highly
optimized method for checking whether a specific element is contained in the
set. This is based on a data structure known as a hash table. Since sets are
unordered, we cannot access items using indexes as we do in lists.
Example:
Add() method:
Clear() method
Output: set()
Amity University Jharkhand, Ranchi
Copy() Method
Difference() Method
Return a set that contains the items that only exist in set x, and not in
set y:
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
z = x.difference(y)
print(z)
Discard Method
Remove "banana" from the set:
fruits ={"apple", "banana", "cherry"}
fruits.discard("banana")
print(fruits)
Output: {'apple', 'cherry'}
Intersection:
Return a set that contains the items that exist in both set x, and set y:
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
z = x.intersection(y)
print(z)
Output: {'apple'}
Intersection_update()
Remove the items that is not present in both x and y:
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"} Output:{'apple'}
x.intersection_update(y)
print(x)
Amity University Jharkhand, Ranchi
Isdisjoint()
Return True if no items in set x is present in set y:
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "facebook"}
z = x.isdisjoint(y) Output: True
print(z)
Issubset()
Return True if all items in set x are present in set y:
x = {"a", "b", "c"}
y = {"f", "e", "d", "c", "b", "a"}
z = x.issubset(y) Output: True
print(z)
Issuperset()
Return True if all items set y are present in set x:
x = {"f", "e", "d", "c", "b", "a"}
y = {"a", "b", "c"} Output: True
z = x.issuperset(y)
print(z)
Pop()
Remove a random item from the set:
fruits = {"apple", "banana", "cherry"}
fruits.pop() Output:{'apple', 'banana'}
print(fruits)
Amity University Jharkhand, Ranchi
Remove()
Remove "banana" from the set:
fruits = {"apple", "banana", "cherry"}
fruits.remove("banana")
print(fruits) output:{'apple', 'cherry'}
Symmetric _difference()
Return a set that contains all items from both sets, except items
that are present in both sets:
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
z = x.symmetric_difference(y)
print(z)
Output:{'microsoft', 'google', 'banana', 'cherry'}
Amity University Jharkhand, Ranchi
Union()
Return a set that contains all items from both sets, duplicates are
excluded:
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
z = x.union(y)
print(z)
Output: {'microsoft', 'banana', 'cherry', 'apple', 'google'}
Update()