0% found this document useful (0 votes)
32 views87 pages

Python Notes Part 2

Lists are mutable sequences that can hold elements of any type. Lists are created using square brackets and elements are accessed via indices starting from 0. Lists have many built-in methods like append(), extend(), sort() etc. Dictionaries are another built-in data type that store mappings of unique keys to values. Dictionaries are created using curly braces and values can be accessed using keys.

Uploaded by

dayaadils123
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
0% found this document useful (0 votes)
32 views87 pages

Python Notes Part 2

Lists are mutable sequences that can hold elements of any type. Lists are created using square brackets and elements are accessed via indices starting from 0. Lists have many built-in methods like append(), extend(), sort() etc. Dictionaries are another built-in data type that store mappings of unique keys to values. Dictionaries are created using curly braces and values can be accessed using keys.

Uploaded by

dayaadils123
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 87

Lists

A list is a sequence
Like a string, a list is a sequence of values.
In a list, the values can be any type. The values in a list are called
elements or sometimes items.
List enclose the elements in square brackets ([ and ]):
[10, 20, 30, 40]
[‘winter', ‘autumn', ‘summer']
Example - List
• The following list contains a string, a float, an integer, and (lo!)
another list:
['spam', 2.0, 5, [10, 20]]
• A list within another list is nested.
Examples
• A list that contains no elements is called an empty list; you can create
one with empty brackets, [].
• As you might expect, you can assign list values to variables:
>>> cheeses = ['Cheddar', 'Edam', 'Gouda’]
>>> numbers = [42, 123]
>>> empty = []
>>> print(cheeses, numbers, empty)
['Cheddar', 'Edam', 'Gouda'] [42, 123] []
Lists are mutable
• The syntax for accessing the elements of a list is the same as for
accessing the characters of a string—the bracket operator.
• The expression inside the brackets specifies the index.
• Remember that the indices start at 0:
• >>> cheeses[0]
• 'Cheddar’
Lists are mutable
• Unlike strings, lists are mutable.
• When the bracket operator appears on the left side of an assignment,
it identifies the element of the list that will be assigned.
>>> numbers = [42, 123]
>>> numbers[1] = 5
>>> numbers
[42, 5]
State Diagram
in operator
• The in operator also works on lists.
>>> cheeses = ['Cheddar', 'Edam', 'Gouda’]
>>> 'Edam' in cheeses
True
>>> 'Brie' in cheeses
False
Length of a List
• Although a list can contain another list, the nested list still counts as a
single element.
• The length of this list is four:
['spam', 1, ['Brie', 'Roquefort', 'Pol le Veq'], [1, 2, 3]]
List operations
• The + operator concatenates lists:
>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> c = a + b
>>> c
[1, 2, 3, 4, 5, 6]
* operator
The * operator repeats a list a given number of times:
>>> [0] * 4
[0, 0, 0, 0]
>>> [1, 2, 3] * 3
[1, 2, 3, 1, 2, 3, 1, 2, 3]
The first example repeats [0] four times.
The second example repeats the list [1, 2, 3] three times.
List slices
The slice operator also works on lists:
>>> t = ['a', 'b', 'c', 'd', 'e', 'f’]
>>> t[1:3]
['b', 'c’]
>>> t[:4]
['a', 'b', 'c', 'd’]
>>> t[3:]
['d', 'e', 'f']
List slices
• So if you omit both, the slice is a copy of the whole list.
>>> t[:]
['a', 'b', 'c', 'd', 'e', 'f']
Updating List
A slice operator on the left side of an assignment can update multiple
elements:
>>> t = ['a', 'b', 'c', 'd', 'e', 'f’]
>>> t[1:3] = ['x', 'y’]
>>> t ['a', 'x', 'y', 'd', 'e', 'f']
List methods
• Python provides methods that operate on lists.
For example, append adds a new element to the end of a list:
>>> t = ['a', 'b', 'c’]
>>> t.append('d’)
>>> t
['a', 'b', 'c', 'd']
List Methods
• extend takes a list as an argument and appends all of the elements:
>>> t1 = ['a', 'b', 'c’]
>>> t2 = ['d', 'e’]
>>> t1.extend(t2)
>>> t1
['a', 'b', 'c', 'd', 'e’]
This example leaves t2 unmodified.
List Methods
• sort arranges the elements of the list from low to high:
>>> t = ['d', 'c', 'e', 'b', 'a’]
>>> t.sort()
>>> t
['a', 'b', 'c', 'd', 'e']
Built-in function
• Adding up the elements of a list is such a common operation that
Python provides it as a built-in function, sum:
>>> t = [1, 2, 3]
>>> sum(t)
6
Deleting elements
• There are several ways to delete elements from a list.
• If you know the index of the element you want, you can use pop:
>>> t = ['a', 'b', 'c’]
>>> x = t.pop(1)
>>> t ['a', 'c’]
>>> x
'b'
del operator
• If you don’t need the removed value, you can use the del operator:
>>> t = ['a', 'b', 'c’]
>>> del t[1]
>>> t
['a', 'c']
remove
• If you know the element you want to remove (but not the index), you
can use remove:
>>> t = ['a', 'b', 'c’]
>>> t.remove('b’)
>>> t
['a', 'c']
del with a slice index
• To remove more than one element, you can use del with a slice index:
>>> t = ['a', 'b', 'c', 'd', 'e', 'f’]
>>> del t[1:5]
>>> t
['a', 'f’]
As usual, the slice selects all the elements up to but not including the
second index.
Lists and strings
• A string is a sequence of characters and a list is a sequence of values.
• To convert from a string to a list of characters, you can use list:
>>> s = 'spam’
>>> t = list(s)
>>> t
['s', 'p', 'a', 'm']
split method
• The list function breaks a string into individual letters.
• If you want to break a string into words, you can use the split method:
>>> s =‘On a rainy day I smile’
>>> t = s.split()
>>> t
[‘On', ‘a', ‘rainy', ‘day’, ’I’, ‘smile’]
Split method with delimiter as argument
• An optional argument called a delimiter specifies which characters to
use as word boundaries.
• The following example uses a hyphen as a delimiter:
>>> s = 'spam-spam-spam’
>>> delimiter = '-’
>>> t = s.split(delimiter)
>>> t
['spam', 'spam', 'spam']
join
• Join is the inverse of split.
• It takes a list of strings and concatenates the elements.
• join is a string method, so you have to invoke it on the delimiter and
pass the list as a parameter:
>>> t = [‘sparrow', ‘robin', ‘myna', ‘parrot’]
>>> delimiter = ‘ ‘
>>> s = delimiter.join(t)
>>> s
‘sparrow robin myna parrot'
Objects and values
• To check whether two variables refer to the same object, you can use
the is operator.
>>> a = [1, 2, 3]
>>> b = [1, 2, 3]
>>> a is b
False
Aliasing
• If a refers to an object and you assign b = a, then both variables refer
to the same object:
>>> a = [1, 2, 3]
>>> b = a
>>> b is a
True
List arguments
• When you pass a list to a function, the function gets a reference to the list.
• If the function modifies the list, the caller sees the change.
• For example, delete_head removes the first element from a list:
def delete_head(t):
del t[0]
Here’s how it is used:
>>> letters = ['a', 'b', 'c’]
>>> delete_head(letters)
>>> letters
['b', 'c']
Append
Here’s an example using append:
>>> t1 = [1, 2]
>>> t2 = t1.append(3)
>>> t1
[1, 2, 3]
>>> t2
None
+ operator(new list)
• Here’s an example using the + operator:
>>> t3 = t1 + [4]
>>> t1
[1, 2, 3]
>>> t3
[1, 2, 3, 4]
The result of the operator is a new list, and the original list is
unchanged.
Dictionaries
• Dictionary is a data structure in which we store values as a pair of key
and value.
• Each key is separated from its value by a colon (:) , and consecutive
items are separated by commas.
• The entire items in a dictionary are enclosed in curly brackets{}.
• The syntax for defining a dictionary is
dictionary_name={Key_1: value_1, key_2: value_2, key_3:value_3}
Dictionaries
• If there are many keys and values in dictionaries, then we can write
just one key_value pair on a line to make the code easier to read and
understand.
Dictionary_name={key_1: value_1,
key_2: value_2,
key_3: value_3,
}
Creating a Dictionary
• The syntax to create a dictionary with key-value pairs is:
dictionary_variable = {key1 : val1, key2 : val2, …}
• To create an empty dictionary, just write the following line of code.
Dict = {}
Print(Dict)

Output
{}
Example
Dict = {‘Roll_No’ : ‘401’, ‘Name’ : ‘Arnav’, ‘Course’ : ‘BTech’}
Print(Dict)

OUTPUT:
{‘Roll_No’ : ‘401’, ‘Name’ : ‘Arnav’, ‘Course’ : ‘BTech’}
dict() function
• To create a dictionary with one or more key-value pairs you can also
use the dict() function.
• The dict() creates a dictionary directly from a sequence of key value
pairs.
print(dict([(‘Roll_No’ : ‘401’), (‘Name’ : ‘Arnav’), (‘Course’ : ‘BTech’)]))

OUTPUT:
{‘Roll_No’ : ‘401’, ‘Name’ : ‘Arnav’, ‘Course’ : ‘BTech’}
Accessing Values
• To access values in a dictionary, square brackets are used along with the key
to obtain its value.
Dict = {‘Roll_No’ : ‘401’, ‘Name’ : ‘Arnav’, ‘Course’ : ‘BTech’}
print(“Dict[ROLL_NO = “, Dict[‘Roll_No’])
Print(“Dict[NAME] = “, Dict[‘Name’])
Print(“Dict[COURSE] = “, Dict[‘Course’])
OUTPUT:
Dict[ROLL_NO] = 401
Dict[NAME] = Arnav
Dict[COURSE] = BTech
Creating Dictionary
• You can create a new dictionary with three items:
>>> flowers = {'one’: ‘rose', 'two': ‘orchid', 'three': ‘daffodils’}
But if you print flowers, you might see:
>>> flowers
{'one': ‘rose', 'three': ‘daffodils', 'two': ‘orchid’}
The order of the key-value pairs might not be the same.
Order of Items
• You can use the keys to look up the corresponding values:
>>> flowers['two’]
‘orchid’
The key 'two' always maps to the value ‘orchid' so the order of the
items doesn’t matter.
len function
• If the key isn’t in the dictionary, you get an exception:
>>> flowers['four’]
KeyError: 'four’
The len function works on dictionaries; it returns the number of key-
value pairs:
>>> len(flowers)
3
in operator
• The in operator works on dictionaries, too; it tells you whether
something appears as a key in the dictionary (appearing as a value is
not good enough).
>>> 'one' in flowers
True
>>> 'uno' in flowers
False
Method values
• To see whether something appears as a value in a dictionary, you can
use the method values, which returns a collection of values, and then
use the in operator:
>>> vals = flowers.values()
>>> ‘rose' in vals
True
Adding Items
• Adding an item to the dictionary is done by using a new index key and
assigning a value to it:
Example
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["color"] = "red"
print(thisdict)
Dictionary Items - Data Types
The values in dictionary items can be of any data type:
Example
String, int, boolean, and list data types:
thisdict = {
"brand": "Ford",
"electric": False,
"year": 1964,
"colors": ["red", "white", "blue"]
}
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.
popitem() method
• The popitem() method removes the last inserted item(in versions
before 3.7, a random item is removed instead):
del keyword
• The del keyword removes the item with the specified key name.
del keyword
• The del keyword can also delete the dictionary completely.
clear() method
• The clear() method empties the dictionary.
Loop Through a Dictionary
• You can loop through the dictionary by using a for loop.
• When looping through a dictionary, the return values are the keys of
the dictionary, but there are methods to return the values as well.
Example
Print all key names in the dictionary, one by one:
for x in thisdict:
print(x)
Loop Through a Dictionary
Example
Print all values in the dictionary, one by one:
for x in thisdict:
print(thisdict[x])
Values() method
• You can also use the values() method to return values of a dictionary.
keys() method
• You can use the keys() method to return the keys of a
dictionary:
Example
• Add a new item to the original dictionary, and see that the keys list gets updated as well:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

x = car.keys()

print(x) #before the change

car["color"] = "white"

print(x) #after the change


Example
• Make a change in the original dictionary, and see that the values list
gets updated as well:
Example for items() method
• Loop through keys and values using the items() method.
thisdict ={
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
for x, y in thisdict.items():
print(x, y)
Copy a Dictionary
• There are ways to make a copy, one way is to use the dictionary
method copy().
Nested Dictionaries
myfamily = {
"child1" : {
"name" : "Emil",
"year" : 2004
},
"child2" : {
"name" : "Tobias",
"year" : 2007
}
}
print(myfamily)
setdefault() method
setdefault() returns the value of a key (if the key is in dictionary). Else, it inserts a key with the
default value to the dictionary.
Syntax
dictionary.setdefault(keyname, value)
Returns:
• Value of the key if it is in the dictionary.
• None if a key is not in the dictionary and default_value is not specified.
• default_value if key is not in the dictionary and default_value is specified.
Dictionary Methods
Tuples
• Tuple is very simple and almost similar to creating a list.
• We need to put the different comma separated values within
paranthesis.
• Values can be an integer, a floating point no., a character, or a string.
Example:
Tup1 = () # creates an empty tuple.
Print(Tup1)
OUTPUT:
()
Example
A tuple is a collection which is ordered and unchangeable.
Create a Tuple:
• thistuple = ("apple", "banana", "cherry")
print(thistuple)
Tuples
Ordered
• When we say that tuples are ordered, it means that the items have a
defined order, and that order will not change.
Unchangeable
• Tuples are unchangeable, meaning that we cannot change, add or
remove items after the tuple has been created.
Allow Duplicates
Tuples allow duplicate values:

thistuple =
("apple", "banana", "cherry", "apple", "cherry")
print(thistuple)
Tuple Length
To determine how many items a tuple has, use the len() function:
Example
Print the number of items in the tuple:

thistuple = ("apple", "banana", "cherry")


print(len(thistuple))
Create Tuple With One Item
• To create a tuple with only one item, you have to add a comma after
the item, otherwise Python will not recognize it as a tuple.
Example
• One item tuple, remember the comma:
• thistuple = ("apple",)
print(type(thistuple))

#NOT a tuple
thistuple = ("apple")
print(type(thistuple))
Tuple Items - Data Types
• Tuple items can be of any data type:
Example
• String, int and boolean data types:
tuple1 = ("apple", "banana", "cherry")
tuple2 = (1, 5, 7, 9, 3)
tuple3 = (True, False, False)
Different data types
• A tuple can contain different data types:
Example
• A tuple with strings, integers and boolean values:
• tuple1 = ("abc", 34, True, 40, "male")
Type()
Demostrate the use of Nested Tuples
Toppers = ((“Sam”, ”BSc”, 92.0),(“Ramya”, ”BCA”, 99.0),(“John”, “Btech”, 97))
for i in Toppers:
print(i)
OUTPUT
(‘Sam’, ‘BSc’, 92.0)
(‘Ramya’, ‘BCA’, 99.0)
(‘John’, ‘Btech’, 97))
Program to demonstrate the use of index()
Tup = (1,2,3,4,5,6,7,8)
print(Tup.index(4))

OUTPUT
3
The ZIP() function
zip() is a built-in function that takes two or more sequences and “zips” them into a
list of tuples.
The tuple thus formed has one element from each sequence.
Example
Tup = (1,2,3,4,5)
List1 = [‘a’, ‘b’, ‘c’, ‘d’, ‘e’]
print(list((zip(Tup, List1))))
OUTPUT
[(1, ‘a’), (2, ‘b’), (3, ‘c’), (4, ‘d’), (5, ‘e’)]
Zip() function on variable-length sequence
Tup = (1,2,3)
List1 = [‘a’ , ’b’ , ’c’ , ’d’ , ’e’]
print(list(zip(Tup, List1)))

OUTPUT
[(1, ‘a’), (2, ‘b’), (3, ‘c’)]
Joining Tuples
Join two tuples together:
a = ("John", "Charles", "Mike")
b = ("Jenny", "Christy", "Monica")

x = zip(a, b)
Sets

• Sets are used to store multiple items in a single variable.


• Set is one of 4 built-in data types in Python used to store collections
of data, the other 3 are List, Tuple, and Dictionary, all with different
qualities and usage.
Example
Create a Set:
thisset = {"apple", "banana", "cherry"}
print(thisset)

EX:
s = {1, 2.0,”abc”}
print(s)
set {1, 2.0, ‘abc’}
set()
• Set() converts a list of different types of values into a set.
Example:
s = set([1,2,’a’,’b’,”def”, 4.56])
print(s)

OUTPUT:
set ([‘a’, 1, 2, ’b’, 4.56, ‘def’])
Add Items
Once a set is created, you cannot change its items, but you can add
new items.
thisset = {"apple", "banana", "cherry"}

thisset.add("orange")

print(thisset)
Add Sets
To add items from another set into the current set, use the update()
method.
thisset = {"apple", "banana", "cherry"}
tropical = {"pineapple", "mango", "papaya"}
thisset.update(tropical)
print(thisset)
Add Any Iterable
• The object in the update() does not have to be a set, it can be any
iterable object (tuples, list, dictionaries, etc)
Example
Add elements of a list to at set:
thisset = {"apple", "banana", "cherry"}
mylist = ["kiwi", "orange"]

thisset.update(mylist)

print(thisset)
Remove Item
• To remove an item in set, use the remove() or the discard() method.

thisset = {"apple", "banana", "cherry"}

thisset.remove("banana")

print(thisset)
discard() method
Remove “banana” by using discard() method.

thisset = {"apple", "banana", "cherry"}

thisset.discard("banana")

print(thisset)
Pop() method
Remove the last item by using pop() method.

thisset = {"apple", "banana", "cherry"}

x = thisset.pop()

print(x)

print(thisset)
clear() method
The clear() method empties the set.

thisset = {"apple", "banana", "cherry"}

thisset.clear()

print(thisset)
del keyword
The del keyword will delete the set completely.

thisset = {"apple", "banana", "cherry"}

del thisset

print(thisset)
Loop items
Loop through the sets and print the values.

thisset = {"apple", "banana", "cherry"}

for x in thisset:
print(x)
Join Two Sets
• The union() method returns a new set with all items from both sets.
set1 = {"a", "b" , "c"}
set2 = {1, 2, 3}

set3 = set1.union(set2)
print(set3)
Keep ONLY the Duplicates- Intersection
Keep the items that exist in both set x and set y
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}

x.intersection_update(y)

print(x)

You might also like