Python Unit 2
Python Unit 2
Python List
You'll learn everything about Python lists; how they are created, slicing of a list, adding or
removing elements from them and so on.
# empty list
my_list = []
# list of integers
my_list = [1, 2, 3]
Also, a list can even have another list as an item. This is called nested list.
# nested list
my_list = ["mouse", [8, 4, 6], ['a']]
There are various ways in which we can access the elements of a list.
We can use the index operator [] to access an item in a list. Index starts from 0. So, a list
having 5 elements will have index from 0 to 4.
Trying to access an element other that, this will raise an IndexError. The index must be an
integer. We can't use float or other types, this will result into TypeError.
Nested list are accessed using nested indexing.
Negative indexing:
Python allows negative indexing for its sequences. The index of -1 refers to the last item, -2 to the
second last item and so on.
We can access a range of items in a list by using the slicing operator (colon).
List are mutable, meaning, their elements can be changed unlike string or tuple.
We can use assignment operator (=) to change an item or a range of items.
We can add one item to a list using append() method or add several items using extend() method.
We can also use + operator to combine two lists. This is also called concatenation.
The * operator repeats a list for the given number of times.
Furthermore, we can insert one item at a desired location by using the method insert ( ) or insert
multiple items by squeezing it into an empty slice of a list.
We can delete one or more items from a list using the keyword del. It can even delete the list
entirely.
We can use remove() method to remove the given item or pop() method to remove an item
at the given index.
The pop() method removes and returns the last item if index is not provided. This helps us
implement lists as stacks (first in, last out data structure).
We can also use the clear( ) method to empty a list.
Finally, we can also delete items in a list by assigning an empty list to a slice of elements.
Methods that are available with list object in Python programming are tabulated below.
List comprehension is an elegant and concise way to create new list from an existing list in
Python.
List comprehension consists of an expression followed by for statement inside square
brackets.
Here is an example to make a list with each item being increasing power of 2.
We can test if an item exists in a list or not, using the keyword in.
Built-in functions like all( ), any( ), enumerate( ), len( ), max( ), min( ), list( ), sorted( ) etc. are
commonly used with list to perform different tasks.
Function Description
all() Return True if all elements of the list are true (or if the list is empty).
any() Return True if any element of the list is true. If the list is empty, return False.
Return an enumerate object. It contains the index and value of all the items of list
enumerate()
as a tuple.
len() Return the length (the number of items) in the list.
list() Convert an iterable (tuple, string, set, dictionary) to a list.
max() Return the largest item in the list.
min() Return the smallest item in the list
sorted() Return a new sorted list (does not sort the list itself).
sum() Return the sum of all elements in the list.
Python Tuple
You'll learn everything about Python tuples. More specifically, what are tuples, how to create
them, when to use them and various methods you should be familiar with.
In Python programming, a tuple is similar to a list. The difference between the two is that we
cannot change the elements of a tuple once it is assigned whereas in a list, elements can be
changed.
Since, tuples are quite similar to lists, both of them are used in similar situations as well.
However, there are certain advantages of implementing a tuple over a list. Below listed are some
of the main advantages:
P. Veera Prakash 6|Page
B.TECH-CSE-IV YEAR II SEM-R13 REGULATION-JNTUA
We generally use tuple for heterogeneous (different) datatypes and list for homogeneous
(similar) datatypes.
Since tuple are immutable, iterating through tuple is faster than with list. So there is a slight
performance boost.
Tuples that contain immutable elements can be used as key for a dictionary. With list, this
is not possible.
If you have data that doesn't change, implementing it as tuple will guarantee that it remains
write-protected.
Creating a Tuple
A tuple is created by placing all the items (elements) inside a parentheses (), separated by
comma. The parentheses are optional but it is a good practice to write it.
A tuple can have any number of items and they may be of different types (integer, float,
list, string etc.).
Having one element within parentheses is not enough. We will need a trailing comma to indicate
that it is in fact a tuple.
There are various ways in which we can access the elements of a tuple.
1. Indexing
We can use the index operator [] to access an item in a tuple where the index starts from 0.
So, a tuple having 6 elements will have index from 0 to 5. Trying to access an element other that
(6, 7,...) will raise an IndexError.
The index must be an integer, so we cannot use float or other types. This will result into
TypeError.
Likewise, nested tuple are accessed using nested indexing, as shown in the example below.
2. Negative Indexing
We can access a range of items in a tuple by using the slicing operator - colon ":".
Slicing can be best visualized by considering the index to be between the elements as shown
below. So if we want to access a range, we need the index that will slice the portion from the tuple.
Changing a Tuple
We can use + operator to combine two tuples. This is also called concatenation.
We can also repeat the elements in a tuple for a given number of times using the *
operator.
Both + and * operations result into a new tuple.
Deleting a Tuple
As discussed above, we cannot change the elements in a tuple. That also means we cannot delete
or remove items from a tuple.
Methods that add items or remove items are not available with tuple. Only the following two
methods are available.
Method Description
P. Veera Prakash 10 | P a g e
B.TECH-CSE-IV YEAR II SEM-R13 REGULATION-JNTUA
Built-in Functions with Tuple
Built-in functions like all(), any(), enumerate(), len(), max(), min(), sorted(), tuple() etc. are
commonly used with tuple to perform different tasks.
Function Description
all() Return True if all elements of the tuple are true (or if the tuple is empty).
Return True if any element of the tuple is true. If the tuple is empty, return
any()
False.
Return an enumerate object. It contains the index and value of all the
enumerate()
items of tuple as pairs.
len() Return the length (the number of items) in the tuple.
max() Return the largest item in the tuple.
min() Return the smallest item in the tuple
Take elements in the tuple and return a new sorted list (does not sort the
sorted()
tuple itself).
sum() Retrun the sum of all elements in the tuple.
tuple() Convert an iterable (list, string, set, dictionary) to a tuple.
Python Sets
You'll learn everything about Python sets; how they are created, adding or removing elements
from them, and all operations performed on sets in Python.
A set is an unordered collection of items. 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.
Sets can be used to perform mathematical set operations like union, intersection, symmetric
difference etc.
A set is created by placing all the items (elements) inside curly braces {}, separated by comma or
by using the built-in function set().
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.
P. Veera Prakash 11 | P a g e
B.TECH-CSE-IV YEAR II SEM-R13 REGULATION-JNTUA
Empty curly braces {} will make an empty dictionary in Python. To make a set without any
elements we use the set() function without any argument.
Sets are mutable. But since they are unordered, indexing have no meaning.
We cannot access or change an element of set using indexing or slicing. Set does not
support it.
P. Veera Prakash 12 | P a g e
B.TECH-CSE-IV YEAR II SEM-R13 REGULATION-JNTUA
We can add single element using the add() method and multiple elements using the
update() method. The update() method can take tuples, lists, strings or other sets as its
argument. In all cases, duplicates are avoided.
P. Veera Prakash 13 | P a g e
B.TECH-CSE-IV YEAR II SEM-R13 REGULATION-JNTUA
The only difference between the two is that, while using discard() if the item does not exist in
the set, it remains unchanged. But remove() will raise an error in such condition.
Similarly, we can remove and return an item using the pop() method.
Set being unordered, there is no way of determining which item will be popped. It is
completely arbitrary.
We can also remove all items from a set using clear().
Sets can be used to carry out mathematical set operations like union, intersection, difference and
symmetric difference. We can do this with operators or methods.
P. Veera Prakash 14 | P a g e
B.TECH-CSE-IV YEAR II SEM-R13 REGULATION-JNTUA
Let us consider the following two sets for the following operations.
>>> A = {1, 2, 3, 4, 5}
>>> B = {4, 5, 6, 7, 8}
Set Union
Set Intersection
P. Veera Prakash 15 | P a g e
B.TECH-CSE-IV YEAR II SEM-R13 REGULATION-JNTUA
>>> A.intersection(B)
{4, 5}
# use intersection function on B
>>> B.intersection(A)
{4, 5}
Set Difference
Difference of A and B (A - B) is a set of elements that are only in A but not in B. Similarly,
B - A is a set of element in B but not in A.
Difference is performed using - operator. Same can be accomplished using the method
difference().
Symmetric Difference of A and B is a set of elements in both A and B except those that are
common in both.
Symmetric difference is performed using ^ operator. Same can be accomplished using the
method symmetric_difference().
P. Veera Prakash 16 | P a g e
B.TECH-CSE-IV YEAR II SEM-R13 REGULATION-JNTUA
{1, 2, 3, 6, 7, 8}
# use symmetric_difference function on B
>>> B.symmetric_difference(A)
{1, 2, 3, 6, 7, 8}
There are many set methods, some of which we have already used above. Here is a list of all the
methods that are available with set objects.
Method Description
add() Add an element to a set
clear() Remove all elements form a set
copy() Return a shallow copy of a set
difference() Return the difference of two or more sets as a new set
difference_update() Remove all elements of another set from this set
Remove an element from set if it is a member. (Do nothing if the
discard()
element is not in set)
intersection() Return the intersection of two sets as a new set
intersection_update() Update the set with the intersection of itself and another
isdisjoint() Return True if two sets have a null intersection
issubset() Return True if another set contains this set
issuperset() Return True if this set contains another set
Remove and return an arbitary set element. Raise KeyError if the
pop()
set is empty
Remove an element from a set. If the element is not a member,
remove()
raise a KeyError
symmetric_difference() Return the symmetric difference of two sets as a new set
symmetric_difference_update() Update a set with the symmetric difference of itself and another
union() Return the union of sets in a new set
update() Update a set with the union of itself and others
P. Veera Prakash 17 | P a g e
B.TECH-CSE-IV YEAR II SEM-R13 REGULATION-JNTUA
Built-in Functions with Set
Built-in functions like all(), any(), enumerate(), len(), max(), min(), sorted(), sum() etc.
are commonly used with set to perform different tasks.
Function Description
all() Return True if all elements of the set are true (or if the set is empty).
any() Return True if any element of the set is true. If the set is empty, return False.
Return an enumerate object. It contains the index and value of all the items of set
enumerate()d
as a pair.
len() Return the length (the number of items) in the set.
max() Return the largest item in the set.
min() Return the smallest item in the set.
sorted() Return a new sorted list from elements in the set(does not sort the set itself).
sum() Retrun the sum of all elements in the set.
Python Frozenset
Frozenset is a new class that has the characteristics of a set, but its elements cannot be
changed once assigned. While tuples are immutable lists, frozensets are immutable sets.
Sets being mutable are unhashable, so they can't be used as dictionary keys. On the other
hand, frozensets are hashable and can be used as keys to a dictionary.
Frozensets can be created using the function frozenset().
This datatype supports methods like copy(), difference(), intersection(), isdisjoint(),
issubset(), issuperset(), symmetric_difference() and union(). Being immutable it does not
have method that add or remove elements.
# initialize A and B
A = frozenset([1, 2, 3, 4])
B = frozenset([3, 4, 5, 6])
>>> A.isdisjoint(B)
P. Veera Prakash 18 | P a g e
B.TECH-CSE-IV YEAR II SEM-R13 REGULATION-JNTUA
False
>>> A.difference(B)
frozenset({1, 2})
>>> A | B
frozenset({1, 2, 3, 4, 5, 6})
>>> A.add(3)
...
AttributeError: 'frozenset' object has no attribute 'add'
Python Dictionary
You'll learn everything about Python dictionary; how they are created, accessing, adding
and removing elements from them and, various built-in methods.
Python dictionary is an unordered collection of items. While other compound data types
have only value as an element, a dictionary has a key: value pair.
Dictionaries are optimized to retrieve values when the key is known.
As you can see above, we can also create a dictionary using the built-in function dict().
While indexing is used with other container types to access values, dictionary uses keys. Key can
be used either inside square brackets or with the get() method.
P. Veera Prakash 19 | P a g e
B.TECH-CSE-IV YEAR II SEM-R13 REGULATION-JNTUA
The difference while using get() is that it returns None instead of KeyError, if the key is not
found.
Dictionary are mutable. We can add new items or change the value of existing items using
assignment operator.
If the key is already present, value gets updated, else a new key: value pair is added to the
dictionary.
We can remove a particular item in a dictionary by using the method pop(). This method removes
as item with the provided key and returns the value.
The method, popitem() can be used to remove and return an arbitrary item (key, value) form the
dictionary. All the items can be removed at once using the clear() method.
We can also use the del keyword to remove individual items or the entire dictionary itself.
P. Veera Prakash 20 | P a g e
B.TECH-CSE-IV YEAR II SEM-R13 REGULATION-JNTUA
Methods that are available with dictionary are tabulated below. Some of them have already been
used in the above examples.
Method Description
P. Veera Prakash 21 | P a g e
B.TECH-CSE-IV YEAR II SEM-R13 REGULATION-JNTUA
Dictionary comprehension is an elegant and concise way to create new dictionary from an
iterable in Python.
Dictionary comprehension consists of an expression pair (key: value) followed by for
statement inside curly braces {}.
Here is an example to make a dictionary with each item being a pair of a number and its
square.
squares = {}
for x in range(6):
squares[x] = x*x
Built-in functions like all(), any(), len(), cmp(), sorted() etc. are commonly used with dictionary to
perform different tasks.
Function Description
all() Return True if all keys of the dictionary are true (or if the dictionary is empty).
any() Return True if any key of the dictionary is true. If the dictionary is empty, return False.
P. Veera Prakash 22 | P a g e
B.TECH-CSE-IV YEAR II SEM-R13 REGULATION-JNTUA
Here are some examples that uses built-in functions to work with dictionary.
Python Strings
P. Veera Prakash 23 | P a g e
B.TECH-CSE-IV YEAR II SEM-R13 REGULATION-JNTUA
If we try to access index out of the range or use decimal number, we will get errors.
Slicing can be best visualized by considering the index to be between the elements as shown
below.
If we want to access a range, we need the index that will slice the portion from the string.
We cannot delete or remove characters from a string. But deleting the string entirely is possible
using the keyword del.
P. Veera Prakash 25 | P a g e
B.TECH-CSE-IV YEAR II SEM-R13 REGULATION-JNTUA
Built-in functions to Work with Python
Various built-in functions that work with sequence, works with string as well.
Some of the commonly used ones are enumerate() and len(). The enumerate() function
returns an enumerate object. It contains the index and value of all the items in the string as
pairs. This can be useful for iteration.
Similarly, len() returns the length (number of characters) of the string.
Escape Sequence
If we want to print a text like -He said, "What's there?"- we can neither use single quote or double
quotes. This will result into SyntaxError as the text itself contains both single and double quotes.
One way to get around this problem is to use triple quotes. Alternatively, we can use escape
sequences.
An escape sequence starts with a backslash and is interpreted differently. If we use single quote to
represent a string, all the single quotes inside the string must be escaped. Similar is the case with
double quotes. Here is how it can be done to represent the above text.
P. Veera Prakash 26 | P a g e
B.TECH-CSE-IV YEAR II SEM-R13 REGULATION-JNTUA
Here is a list of all the escape sequence supported by Python.
>>> print("C:\\Python32\\Lib")
C:\Python32\Lib
Sometimes we may wish to ignore the escape sequences inside a string. To do this we can place r
or R in front of the string. This will imply that it is a raw string and any escape sequence inside it
will be ignored.
The format() method that is available with the string object is very versatile and powerful in
formatting strings. Format strings contains curly braces {} as placeholders or replacement fields
which gets replaced.
The format() method can have optional format specifications. They are separated from field
name using colon. For example, we can left-justify <, right-justify > or center ^ a string in the
given space. We can also format integers as binary, hexadecimal etc. and floats can be rounded or
displayed in the exponent format. There are a ton of formatting you can use. Visit here for all the
string formatting available with the format() method.
We can even format strings like the old sprintf() style used in C programming language. We use
the % operator to accomplish this.
>>> x = 12.3456789
>>> print('The value of x is %3.2f' %x)
The value of x is 12.35
>>> print('The value of x is %3.4f' %x)
The value of x is 12.3457
P. Veera Prakash 28 | P a g e
B.TECH-CSE-IV YEAR II SEM-R13 REGULATION-JNTUA
There are numerous methods available with the string object. The format() method that we
mentioned above is one of them. Some of the commonly used methods are lower(), upper(),
join(), split(), find(), replace() etc. Here is a complete list of all the built-in methods to
work with strings in Python.
>>> "PrOgRaMiZ".lower()
'programiz'
>>> "PrOgRaMiZ".upper()
'PROGRAMIZ'
>>> "This will split all words into a list".split()
['This', 'will', 'split', 'all', 'words', 'into', 'a', 'list']
>>> ' '.join(['This', 'will', 'join', 'all', 'words', 'into', 'a', 'string'])
'This will join all words into a string'
>>> 'Happy New Year'.find('ew')
7
>>> 'Happy New Year'.replace('Happy','Brilliant')
'Brilliant New Year'
P. Veera Prakash 29 | P a g e