CH3 PWP Updated
CH3 PWP Updated
Defining lists, accessing values in list, deleting values in list, updating lists.
Defining a List
Creating a list is as simple as putting different comma-separated values between square
brackets. For example
Subject = “Python”
Left --> 0 1 2 3 4 5
P y t h o n
Right --> -6 -5 -4 -3 -2 -1
For example-
list1 = ['PWP', 'MAD', 6, 20, 'MAN', 'WBP']
print(list1[2]) #accessing single element from left side of
index 2
OUTPUT
6
[6, 20, 'MAN']
[20, 'MAN', 'WBP']
['PWP', 'MAD', 6]
MAN
[6]
For example-
list1 = ['PWP', 'MAD', 6, 20, 'MAN', 'WBP']
del(list1[2]) #deleting single element from left side of index 2
Updating Lists
We can update single or multiple elements of lists by giving the slice on the left-hand side of
the assignment operator, and can add elements in a list with the append() method.
For example-
list.append(element)
a.append(b)
print(a)
Output
extend ()
The extend () method appends an multiple elements to the end of the list.
list.extend(iterable)
a.extend(b)
print(a)
Output
clear ()
list.clear()
L2 = L.copy()
print(L2)
Output
count ()
The count() method returns the number of elements with the specified element.
list.count(element)
cnt = L.count("c")
print(cnt)
Output
index ()
The index() method returns the position at the first occurrence of the specified
element.
The index() method only returns the first occurrence of the value.
list.count(element)
x = L.index(64)
print(x)
Output
insert ()
The insert() method inserts the specified value at the specified position.
Syntax:
list.insert(position, element)
Exmaple:
L.insert(3,68)
print(L)
Output
pop ()
Syntax:
E=list.pop(position)
Exmaple:
E=L.pop(3)
print(E)
print(L)
Output
32
The remove() method removes the first occurrence of the element with the specified
value.
If element with specified value not available in list then Value_Error will be
generated.
Syntax:
list.remove(position)
Exmaple:
L.remove(55)
print(L)
Output
reverse ()
Syntax:
list.reverse()
Exmaple:
L.reverse()
print(L)
Output
o The sort() method sorts the list ascending or descending order, by default
sorting is done in ascending order.
o To sort in descending order use first argument i.e. reverse make its value to
True.
o You can also make a function to decide the sorting criteria(s).
Syntax:
list.sort(reverse=True/False,key=myfunc)
Exmaple:
def myfunc(e1):
return len(e1)
L=['MECH','COMPUTER','CIVIL','ROBOTICS','CIVIL1']
L.sort(reverse=True,key=myfunc)
print(L)
Output
TUPLE
A tuple is a sequence of immutable Python objects. Tuples are sequences, just like lists. The differences
between tuples and lists are, the tuples cannot be changed unlike lists and tuples use parentheses,
whereas lists use square brackets.
Creating a Tuple
Creating a tuple is as simple as putting different comma separated values. Optionally you can put these
comma-separated values between parentheses also. Like string indices, tuple indices start at 0 and they
can be sliced, concatenated, and so on.
Example
tup1 = ('physics', 'chemistry', 1997, 2000);
tup2 = (1, 2, 3, 4, 5 );
tup3 = "a", "b", "c", "d";
To write a tuple containing a single value you have to include a comma, even though there is only one
value.
tup1 = (50,);
Accessing Values in Tuples
To access values in tuple, use the square brackets for slicing along with the index or indices to
Example:
tup1 = ('physics', 'chemistry', 1997, 2000);
tup2 = (1, 2, 3, 4, 5, 6, 7 );
print(tup1[0]);
print(tup2[1:5]);
Output:
physics
[2, 3, 4, 5]
Updating Tuples: Tuples are immutable which means you cannot update or change
the values of tuple elements. You are able to take portions of existing tuples to create
new tuples.
Example:
tup1 = (12, 34.56);
tup2 = ('abc', 'xyz');
# following action is not valid for tuples
# tup1[0] = 100;
# So let's create a new tuple as follows
tup3 = tup1 + tup2;
print(tup3);
Output:
(12, 34.56, 'abc', 'xyz')
Example:
tup = ('physics', 'chemistry', 1997, 2000);
print(tup);
del(tup);
SET
Every element is unique (no duplicates) and must be immutable (which cannot be changed).
However, the set itself is mutable. We can add or remove items from it.
How to Define
A set is created by placing all the items (elements) inside curly braces {}, separated by
comma or by using the built-in function set().
For Example:
S = {10,20,30,40}
S={'Programming', 'Networking', 'Database'}
S={('Programming', 'Python'), ('Networking', 'Database')}
It can have any number of items and they may be of different types (integer, float, tuple,
string etc.).
But a set cannot have a mutable element, like list, set or dictionary, as its element.
Access Items
We cannot access items in a set by referring to an index, since sets are unordered the items
has no index.
But we can loop through the set items using a for loop, or ask if a specified value is present
in a set, by using the in keyword.
To add more than one item to a set use the update() method.
add(item)
print(S)
update(list of items)
S={'Programming', 'Networking',
'Database', 'Data Science'}
S.update(['Java','CCNA','Oracle'])
print(S)
remove(item)
S={'Programming', 'Networking',
'Database', 'Data Science', 'Java','CCNA','Oracle'}
S.remove('Data Science')
print(S)
If the item to remove does not exist, remove() will raise an error.
discard(item)
S={'Programming', 'Networking',
'Database', 'Java','CCNA','Oracle'}
S.discard('Java')
print(S)
If the item to remove does not exist, discard() will not raise an error.
pop()
S={'Programming', 'Networking',
'Database','CCNA','Oracle'}
e=S.pop()
print(e) # e will contain item which is removed
clear()
print(S)
Operations on Set
union()
The union() method returns a new set with all items from both sets.
set3 = set1.union(set2)
print(set3)
intersection()
Return a set that contains the items that exist in both set x, and set y.
z = x.intersection(y)
print(z)
difference()
Return a set that contains the items that only exist in set calling set object (x),
and not in set passed as argument (y).
x.difference_update(y) #x=x–y
print(z)
Method Description
difference_update() Removes the items in this set that are also included in another, specified
set
intersection_update() Removes the items in this set that are not present in other, specified
set(s)
symmetric_difference_update() inserts the symmetric differences from this set and another
Dictionary
Dictionaries are used to store data values in key:value pairs. Keys in dictionaries are unique.
How to Define
Dictionaries are written with curly brackets, and have keys and values:
For Example:
D1= {
"Name": "Aman",
"Dept": "Computer",
"Year": 2020
}
print(D1)
A dictionary is a collection which is ordered, changeable and does not allow duplicates.
As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier, dictionaries
are unordered.
Dictionary Items
The values in dictionary items can be of any data type
D1= {
"Name": "Aman",
"Dept": "Computer",
"Year": 2020,
"Subject": ['MGT','MAD','WBP','PWP'],
"result":{'FY':67,'SY':78,'TY':89}
}
Accessing Items
You can access the items of a dictionary by referring to its key name, inside square brackets:
D1= {
"Name": "Aman",
"Dept": "Computer",
"Year": 2020
}
print(D1[‘Dept’])
Output
Computer
Update Dictionaries
You can change the value of a specific item by referring to its key name:
Change the "year" to 2018:
D1= {
"Name": "Aman",
"Dept": "Computer",
"Year": 2020
}
D1["Year"] = 2021
print(D1[‘Year’])
Output
2021
Methods in Dictionary
get()
The get() method returns the value of the item with the specified key.
dict_class_object.get(key, value)
Key: Required. The key of the element or item you want to get the
value from
D1= {
"Name": "Aman",
"Dept": "Computer",
"Year": 2020
}
s = D1.get("Name", "Student")
print(s)
Output
Aman
keys()
The keys() method will return a list of all the keys in the dictionary.
D1= {
"Name": "Aman",
"Dept": "Computer",
"Year": 2020
}
s = D1.keys()
print(s)
Output
dict_keys(['Name', 'Dept', 'Year'])
values ()
The values () method will return a list of all the values in the dictionary.
D1= {
"Name": "Aman",
"Dept": "Computer",
"Year": 2020
}
v = D1.values()
print(v)
Output
dict_values(['Aman', 'Computer', 2020])
items()
The items() method will return each item in a dictionary, as tuples in a list.
D1= {
"Name": "Aman",
"Dept": "Computer",
"Year": 2020
}
i = D1.items()
print(i)
Output
dict_items([('Name', 'Aman'), ('Dept', 'Computer'), ('Year', 2020)])
update()
The update() method will update the dictionary with the items from the given argument.
D1= {
"Name": "Aman",
"Dept": "Computer",
"Year": 2020
}
D1.update({'subject':['MGT','MAD','WBP','PWP']})
print(D1)
Output
{'Name': 'Aman', 'Dept': 'Computer', 'Year': 2020, 'subject': ['MGT', 'MAD', 'WBP', 'PWP']}
pop()
The pop() method removes the item with the specified key name:
D1= {
"Name": "Aman",
"Dept": "Computer",
"Year": 2020,
"subject":['MGT','MAD','WBP','PWP']
}
i = D1.pop('subject')
Output
Removed Item value is ['MGT', 'MAD', 'WBP', 'PWP']
popitem()
The popitem() method removes the last inserted item or a random item is removed instead.
(before version 3.7).
The pop() method removes the item with the specified key name:
D1= {
"Name": "Aman",
"Dept": "Computer",
"Year": 2020,
}
i = D1.popitem()
Output
Removed Item is ('Year', 2020)
Loop Through a Dictionary
D1= {
"Name": "Aman",
"Dept": "Computer",
"Year": 2020
}
for x in D1:
print(x)
Output
Name
Dept
Year
Method Description
items() Returns a list containing a tuple for each key value pair
keys() Returns a list containing the dictionary's keys
setdefault() Returns the value of the specified key. If the key does not exist: insert the key, with the
specified value