Professional Documents
Culture Documents
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.
Example :
my_list = ['p','r','o','b','e']
print(my_list[0])
print(my_list[2])
print(my_list[4])
# Nested List
n_list = ["Happy", [2,0,1,5]]
print(n_list[0][1])
print(n_list[1][3])
output: p
o
e
a
5
Page 2
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.
Example :
my_list = ['p','r','o','b','e']
# Output: e
print(my_list[-1])
# Output: p
print(my_list[-5])
output: e
p
# elements beginning to
4th print(my_list[:-5])
# elements beginning to
end print(my_list[:])
# Output: [1, 4, 6, 8]
print(odd)
Page 3
# Output: [1, 3, 5, 7]
print(odd)
output: [1, 4, 6, 8]
[1, 3, 5, 7]
We can add one item to a list using append() method or add several items using extend() method.
odd = [1, 3, 5]
odd.append(7)
print(odd)
# Output: [1, 3, 5, 7]
odd.extend([9, 11, 13])
print(odd)
# Output: [1, 3, 5, 7, 9, 11, 13]
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.
odd = [1, 3, 5]
print(odd + [9, 7, 5])
# Output: [1, 3, 5, 9, 7, 5]
print(["re"] * 3) #Output:
["re", "re", "re"]
Functional Programming:
Functional Programming decomposes a problem into a set of functions. The map(),filter(),and reduce()
function It is recommended to use list comprehensions instead of these functions where possible.
Page 8
Tuples
A tuple is a collection which is ordered and unchangeable. In Python tuples are written with round
brackets(parentheses) 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. The values stored in a tuple
can be any type, and they are indexed by integers.
Creating a Tuple:
A tuple is created by placing all the items (elements) inside a parentheses (), separated by comma. The
parentheses are optional but 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.).
Example :
# empty tuple
my_tuple = ()
print(my_tuple)
# nested tuple
my_tuple = ("mouse", [8, 4, 6], (1, 2, 3))
print(my_tuple)
output:
()
(1, 2, 3)
(1, 'Hello', 3.4)
('mouse', [8, 4, 6], (1, 2, 3))
(3, 4.6, 'mic')
3
4.6
mic
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.
Example :
my_tuple = ('p','e','r','m','i','t')
print(my_tuple[0])
print(my_tuple[5])
#print(my_tuple[6]) ------------- # IndexError: list index out of range
#my_tuple[2.0] ---------- # TypeError: list indices must be integers, not float
# nested tuple
n_tuple = ("mouse", [8, 4, 6], (1, 2, 3))
print(n_tuple[0][3])
print(n_tuple[1][1])
output: p
t
s
4
Page 10
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.
Example :
my_tuple = ('p','e','r','m','i','t')
print(my_tuple[-1])
print(my_tuple[-6])
output: t
p
Slicing:
We can access a range of items in a tuple by using the slicing operator - colon " : ".
Example :
my_tuple = ('p','r','o','g','r','a','m','i','z')
# elements beginning to
end print(my_tuple[:])
Changing a Tuple:
This means that elements of a tuple cannot be changed once it has been assigned. But, if the element is itself a
mutable datatype like list, its nested items can be changed. We can also assign a tuple to different values
(reassignment).
Example :
my_tuple = (4, 2, 3, [6, 5])
#my_tuple[1] = 9
# TypeError: 'tuple' object does not support item assignment
my_tuple[3][0] = 9
# but item of mutable (list)element can be changed
print(my_tuple)
Page 11
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.
# Concatenation
print((1, 2, 3) + (4, 5, 6))
# Repeat
print(("Repeat",) * 3)
output: (1, 2, 3, 4, 5, 6)
('Repeat', 'Repeat', 'Repeat')
Deleting a Tuple:
Since tuples are immutable, it is not possible to delete individual elements of a tuple, however, we can
delete the whole tuple itself.
> t = (1, "abc", 3.0)
> del t
> t # If we try to access the tuple after deleting it, python will raise an error
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 't' is not defined
Page 12
Method Description
my_tuple = ('a','p','p','l','e',)
print(my_tuple.count('p'))
print(my_tuple.index('p'))
output: 2
1
Sets
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.
create a set: 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.).
Example:
# set of integers
my_set = {1, 2, 3}
print(my_set)
output: {1, 2, 3}
{'Hello', 1.0, (1, 2, 3)}
Example:
# set do not have duplicates
my_set = {1,2,3,4,3,2}
print(my_set)
# Output: {1, 2, 3, 4}
Page 13
Creating an empty set: 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.
Example:
a = {}
# check data type of a
print(type(a))
a = set()
# check data type of a
print(type(a))
Example:
# initialize my_set
my_set = {1,3}
print(my_set)
# add an element
# Output: {1, 2, 3}
my_set.add(2)
print(my_set)
output: {1, 3}
{1, 2, 3}
{1, 2, 3, 4}
{1, 2, 3, 4, 5, 6, 8}
# discard an element
# Output: {1, 3, 5, 6}
my_set.discard(4)
print(my_set)
# remove an element
# Output: {1, 3, 5}
my_set.remove(6)
print(my_set)
# discard an element
# not present in my_set
# Output: {1, 3, 5}
my_set.discard(2)
print(my_set)
# remove an element
# not present in my_set
# you will get an error.
# Output: KeyError: 2
my_set.remove(2)
output: {1, 3, 4, 5, 6}
{1, 3, 5, 6}
{1, 3, 5}
{1, 3, 5}
Traceback (most recent call last):
File "<stdin>", line 27, in <module>
my_set.remove(2)
KeyError: 2
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().
Page 15
Example:
# initialize my_set
# Output: set of unique elements
my_set = set("HelloWorld")
print(my_set)
# pop an element
# Output: random element
print(my_set.pop())
# clear my_set
my_set.clear()
print(my_set)
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 Union of A and B is a set of all elements from both sets. Union is performed using | operator. Same
can be accomplished using the method union().
Example:
print(A | B)
A.union(c)
Output: {1, 2, 3, 4, 5, 6, 7, 8}
{1, 2, 3, 4, 5, 10, 20, 30, 40}
Set Intersection:
Intersection of A and B is a set of elements that are common in both sets. Intersection is performed using &
operator. Same can be accomplished using the method intersection().
Example:
Output: {4, 5}
{2, 3}
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().
Example:
# initialize A and B
A = {1, 2, 3, 4, 5} B
= {4, 5, 6, 7, 8}
# use - operator on
A print(A - B)
print(B - A)
A.difference(B)
Output: {1, 2, 3}
{8, 6, 7}
{1, 2, 3}
Example:
# initialize A and B
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
# use ^ operator print(A ^
B)
A.symmetric_difference(B)
Output: {1, 2, 3, 6, 7, 8}
{1, 2, 3, 6, 7, 8}
Page 18
Page 19
Dictionaries
A real-life dictionary holds words and their meanings. As you can imagine, likewise, Python dictionary is
an unordered collection of items. While other compound data types have only value as an element, a
dictionary holds key-value pairs.
create a dictionary:
Creating a dictionary is as simple as placing items inside curly braces {} separated by comma. An item has a
key and the corresponding value expressed as a pair, key: value. While values can be of any data type and can
repeat, keys must be of immutable type (string, tuple with immutable elements) and must be unique.
# empty dictionary
my_dict = {}
# using dict()
my_dict = dict({1:'apple', 2:'ball'})
output: Srikanth
26
Traceback (most recent call last):
File "<stdin>", line 11, in <module>
my_dict['address']
KeyError: 'address'
# add item
my_dict['address'] = 'Vijayawada'
print(my_dict)
Example:
# create a dictionary
squares = {1:1, 2:4, 3:9, 4:16, 5:25}
# Output: {2: 4, 3: 9}
print(squares)
# Output: {}
print(squares)
# Throws Error
print(squares)
output: 16
{1: 1, 2: 4, 3: 9, 5: 25}
(1, 1)
{2: 4, 3: 9, 5: 25}
{2: 4, 3: 9}
{}
# Output: True
print(1 in squares)
output: True
True
False
output: 1
9
81
25
49
Page 23
Page 24
Sequences
A sequence is a group of items with a deterministic ordering. The order in which we put them in is the order
in which we get an item out from them. Python offers six types of sequences.
Strings:
A string is a group of characters. Computers do not deal with characters, they deal with numbers (binary). Even
though you may see characters on your screen, internally it is stored and manipulated as a combination of 0's
and 1's.
This conversion of character to a number is called encoding, and the reverse process is decoding. ASCII and
Unicode are some of the popular encoding used.
In Python, string is a sequence of Unicode character. A string is a sequence of characters. We can use a pair of
single or double quotes. And like we’ve always said, Python is dynamically-typed. Every string object is of the
type ‘str’.
Create a string:
Strings can be created by enclosing characters inside a single quote or double quotes. Even triple quotes can be
used in Python but generally used to represent multiline strings and docstrings.
Example:
my_string = 'Hello'
print(my_string)
my_string = "Hello"
print(my_string)
my_string = '''Hello'''
Page 25
print(my_string)
output: Hello
Hello
Hello
Hello, welcome to
the world of Python
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 string by using the slicing operator (colon).
Example:
str = 'programiz'
print('str = ', str)
#first character
print('str[0] = ', str[0])
#last character
print('str[-1] = ', str[-1])
if we try to access index out of the range or use decimal number, we will get errors.
# index must be in range
>>>srikanth="welcome"
>>> srikanth[10]
IndexError: string index out of range
Page 26
We cannot delete or remove characters from a string. But deleting the string entirely is possible using
the keyword del.
> del my_string[1]
...
TypeError: 'str' object doesn't support item deletion
> del my_string
> my_string
...
NameError: name 'my_string' is not defined
Example:
count = 0
for letter in 'Hello World':
if(letter == 'l'):
count += 1
print(count,'letters found')
Bytes Sequences:
The function bytes() returns an immutable bytes object.
> a=bytearray(2)
> a
Page 27
bytearray(b'\x00\x00')
> a=bytearray(5)
> a
bytearray(b'\x00\x00\x00\x00\x00')
a[4]=3
Traceback (most recent call last):
File "<pyshell#46>", line 1, in <module>
a[4]=3
Bytes Arrays:
A bytesarray object is like a bytes object, but it is mutable. It returns an array of the given byte size.
> a=bytearray(5)
> a
bytearray(b'\x00\x00\x00\x00\x00')
> bytearray([1,2,3,4])
bytearray(b'\x01\x02\x03\x04')
> bytearray([1,2,3,4,5])
bytearray(b'\x01\x02\x03\x04\x05')
> a[4]=3
> a
bytearray(b'\x00\x00\x00\x00\x03')
Operations on Sequences:
1. Concatenation
2. Membership
3. Python Slice
Functions on Sequences:
1. len()
2. min() and max()
Methods on Sequences:
1. Python index()
This method returns the index of the first occurrence of a value.
> 'banana'.index('n')
>>>2
2. Python count()
count() returns the number of occurrences of a value in a sequence.
> 'banana'.count('na')
>>>2
Page 28
Comprehensions
Comprehensions are constructs that allow sequences to be built from other sequences. Python 2.0 introduced
list comprehensions and Python 3.0 comes with dictionary and set comprehensions.
List Comprehensions:
A list comprehension consists of the following parts:
An Input Sequence.
A Variable representing members of the input sequence.
An Optional Predicate expression.
An Output Expression producing elements of the output list from members of the Input Sequence
that satisfy the predicate.
Syntax: {expression(variable) for variable in input_set [predicate]
Ex:
Ex:
> [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
list_a = [1, 2, 3, 4]
list_b = [2, 3, 4, 5]
common_num = []
for a in list_a:
for b in list_b:
if a == b:
common_num.append(a)
print(common_num)
Output [2, 3, 4]
Set Comprehension
A set comprehension is similar to a list comprehension, but returns a set and not a list. Syntactically, we use
curly brackets instead of square brackets to create a set.
Example 1
> {s for s in [1, 2, 1, 0]}
set([0, 1, 2])
> {s**2 for s in [1, 2, 1,
0]} set([0, 1, 4])
> {s**2 for s in range(10)}
set([0, 1, 4, 9, 16, 25, 36, 49, 64, 81])
Page 30
Example 2
> {(m, n) for n in range(2) for m in range(3,
5)} set([(3, 0), (3, 1), (4, 0), (4, 1)])
Example 3
generate a set of all of the prime numbers that are less than 100.
r= {x for x in range(2, 101)
if not any(x % y == 0 for y in range(2, x))}
output:
{2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97}
Example 4
> s = { x for x in range(10) }
> s
set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
Dictionary Comprehension:
Dictionary is an unordered collection of items. , a dictionary holds key-value pairs. Creating a dictionary is as
simple as placing items inside curly braces {} separated by comma.
A dictionary comprehension takes the form {key: value for (key, value) in iterable}