Python Module 3
Python Module 3
String is a sequence
A string is a sequence of characters.
we can access the characters one at a time with the [] bracket operator:
fruit=‘banana’
letter=fruit[1]
The second statement selects character number 1 from fruit and assigns
it to letter.
The expression in brackets is called an index. The index indicates which
character in the sequence you want (hence the name).
print (letter)
Output:
a
For most people, the first letter of ‘banana’ is b, not a. But for computer
scientists, the index is an offset from the beginning of the string, and
the offset of the first letter is zero.
fruit=‘banana’
letter=fruit[0]
print (letter)
Output:
b
letter= fruit[1.5]
TypeError: String indices must be integers not float
Program
>>> fruit='banana'
>>> fruit
'banana'
>>> letter=fruit[1]
>>> letter
'a'
>>> print(letter)
a
>>> letter=fruit[0]
>>> letter
'b'
>>> print(letter)
b
>>> letter=fruit[1.5]
Traceback (most recent call last):
File "<pyshell#8>", line 1, in <module>
letter=fruit[1.5]
TypeError: string indices must be integers
Len Function
len is a built-in function that returns the number of characters in a
string.
fruit=‘banana’
len(fruit)
Output:
6
(Or)
fruit='banana'
length=len(fruit)
print(length)
output:
6
To get the last letter of a string,
last=fruit[length-1]
print(last)
Output:
a
Program
fruit='banana'
length=len(fruit)
print(length)
last=fruit[length]
print(last)
output
6
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
last=fruit[length]
IndexError: string index out of range
>>> last=fruit[length-1]
>>> last
'a'
This loop traverses the string and displays each letter on a line by itself.
The last character accessed is the one with the index len(fruit)-1, which
is the last character in the string.
Each time through the loop, the next character in the string is assigned
to the variable char. The loop continues until no characters are left.
Program-1
fruit='banana'
for char in fruit:
print(char)
Output
b
a
n
a
n
a
using while loop
Program-2
fruit='banana'
index=0
while(index<len(fruit)):
letter=fruit[index]
print(letter)
index=index+1
Output
b
a
n
a
n
a
Program-3
prefixies='JKLMNOP'
suffix='ack'
for letter in prefixies:
print(letter+suffix)
Output
Jack
Kack
Lack
Mack
Nack
Oack
Pack
String Slices
A segment of a string is called a slice. Selecting a slice is similar to
selecting a character.
The operator [n:m] returns the part of the string from the “n-eth”
character to the “m-eth” character, including the first but excluding the
last. This behavior is counterintuitive, but it might help to imagine the
indices pointing between the characters.
If you omit the first index (before the colon), the slice starts at the
beginning of the string.
If you omit the second index, the slice goes to the end of the string.
If the first index is greater than or equals to the second the result is an
empty string, represented by two quotation marks.
An empty string contains no characters and has length 0, but other than
that, it is the same as any other string.
Program
s='monthy python'
print(s[0:5])
print(s[6:12])
fruit='banana'
print(fruit[:3])
print(fruit[3:])
print(fruit[3:3])
Output
month
pytho
ban
ana
greeting=‘Hello World’
Greeting[0]=‘j’
print(greeting)
TypeError: String assignment doesnot support item assignment
The reason for the error is that strings are immutable, which means you
can’t change an existing string. The best you can do is create a new string
that is a variation on the original.
Program
greeting='Hello World'
new_greeting='j'+greeting[1:]
print(new_greeting)
Output
jello World
Searching
In a sense, find is the opposite of the [] operator. Instead of taking an
index and extracting the corresponding character, it takes a character
and finds the index where that character appears. If the character is not
found, the function returns -1
If the character doesn’t appear in the string, the program exits the loop
normally and returns -1
Program
def find(word,letter):
index=0
while(index<len(word)):
if(word[index]==letter):
return index
index=index+1
return -1
print(find('hello','l'))
Output
2
Looping and Counting
This program demonstrates another pattern of computation called a counter.
The variable count is initialized to 0 and then incremented each time an ‘a’ is
found. When the loop exits, count contains the result—the total number of a’s.
Program
word='banana'
count=0
for letter in word:
if letter=='a':
ch=letter
count=count+1
print(ch,count)
Output
a 3
String Methods
A method is similar to a function—it takes arguments and returns a
value—but the syntax is different. For example, the method upper takes
a string and returns a new string with all uppercase letters.
This form of dot notation specifies the name of the method, upper, and
the name of the string to apply the method to, word. The empty
parentheses indicate that this method takes no argument.
1. find()
Returns index of first occurrence of the given substring. If it is not
available then we will get -1
Syntax:
s.find(substring)
Program-2
s="durgaravipavanshiva"
print(s.find('a'))
print(s.find('a',7,15))
print(s.find('z',7,15))
Output
4
10
-1
2. rfind()
rfind() method returns the highest index of the substring if found in
given string. If not found then it returns -1.
Syntax:
string.rfind(value, start, end)
Program
txt = 'Hello, welcome to my world.'
x = txt.rfind("e", 5, 10)
print(x)
Output
8
3. index() method
index() method is exactly same as find() method except that if the
specified substring is not available then we will get ValueError.
Syntax:
string.index(element)
Program
vowels = ['a', 'e', 'i', 'o', 'i', 'u']
index = vowels.index('e')
print('The index of e:', index)
Output
The index of e: 1
4. rindex():
The rindex() method returns the highest index of the substring inside
the string (if found). If the substring is not found, it raises an exception
Syntax:
string.rindex(value, start, end)
Program-1
quote = 'Let it be, let it be, let it be'
result = quote.rindex('let it')
print("Substring 'let it':", result)
Output
Substring 'let it': 22
Program-2
txt = 'Hello, welcome to my world.'
x = txt.rindex("e", 5, 10)
print(x)
Output
8
Output
6
4
2
Program-1
s="Learning Python is very difficult"
s1=s.replace("difficult","easy")
print(s1)
Output
Learning Python is very easy
Program-2
txt = "one one was a race horse, two two was one too."
x = txt.replace("one", "three", 2)
print(x)
Output
Three three was a race horse, two two was one too
7. Splitting of Strings
split() method returns a list of strings after breaking the given string
by the specified separator.
Syntax:
str.split(separator, maxsplit)
Program
text = 'Hello python students'
# Splits at space
print(text.split())
word = 'Hello, python, students'
# Splits at ','
print(word.split(','))
word = 'Hello:python:students'
# Splitting at ':'
print(word.split(':'))
word = 'CatBatSatFatOr'
# Splitting at 3
print([word[i:i+3] for i in range(0, len(word), 3)])
Output
['Hello', 'python', 'students']
['Hello', ' python', ' students']
['Hello', 'python', 'students']
['Cat', 'Bat', 'Sat', 'Fat', 'Or']
8. Joining of Strings
The join() string method returns a string by joining all the elements of
an iterable, separated by a string separator.
The join() method provides a flexible way to create strings from
iterable objects. It joins each element of an iterable (such as list,
string, and tuple) by a string separator (the string on which the join()
method is called) and returns the concatenated string.
Syntax:
string.join(iterable)
Program
# .join() with lists
numList = ['1', '2', '3', '4']
separator = ', '
print(separator.join(numList))
# .join() with tuples
numTuple = ('1', '2', '3', '4')
print(separator.join(numTuple))
s1 = 'abc'
s2 = '123'
# each element of s2 is separated by s1
# '1'+ 'abc'+ '2'+ 'abc'+ '3'
print('s1.join(s2):', s1.join(s2))
# each element of s1 is separated by s2
# 'a'+ '123'+ 'b'+ '123'+ 'b'
print('s2.join(s1):', s2.join(s1))
Output
1, 2, 3, 4
1, 2, 3, 4
s1.join(s2): 1abc2abc3
s2.join(s1): a123b123c
Program
s='learning Python is very Easy'
print(s.upper())
print(s.lower())
print(s.swapcase())
print(s.title())
print(s.capitalize())
Output
LEARNING PYTHON IS VERY EASY
learning python is very easy
LEARNING pYTHON IS VERY eASY
Learning Python Is Very Easy
Learning python is very easy
Program
print('Durga786'.isalnum())
print('durga786'.isalpha())
print('durga'.isalpha())
print('durga'.isdigit())
print('786786'.isdigit())
print('abc'.islower())
print('Abc'.islower())
print('abc123'.islower())
print('ABC'.isupper())
print('Learning python is Easy'.istitle())
print('Learning Python Is Easy'.istitle())
print(' '.isspace())
Output
True
False
True
False
True
True
False
True
True
False
True
True
In Operator:
The word in is a Boolean operator that takes two strings and returns True
if the first appears as a substring in the second.
With well-chosen variable names, Python sometimes reads like English.
You could read this loop, “for (each) letter in (the first) word, if (the)
letter (appears) in (the second) word, print (the) letter.”
Program
def in_both(word1,word2):
for letter in word1:
if letter in word2:
print(letter)
in_both('apples','oranes')
Output
a
e
s
String Comparison
Python does not handle uppercase and lowercase letters the same way
that people do. All the uppercase letters come before all the lowercase
letters.
Program
word="orange"
if word=='banana':
print('All right, bananas')
if word<'banana':
print('your word,'+word+',comes before banana')
else:
print('your word,'+word+',comes after banana')
Output
your word,orange,comes after banana
Lists
List is a sequence:
Like a string, a list is a sequence of values. In a string, the values are
characters; in a list, they can be any type. The values in a list are called
elements or sometimes items.
There are several ways to create a new list; the simplest is to enclose the
elements in square brackets ([ and ]):
[10,20,30,40] [‘a’,’b’,’c’,’d’]
The first example is a list of four integers. The second is a list of four
strings.
The elements of a list don’t have to be the same type. The following list
contains a string, a float, an integer, and another list.
Eg: [‘spam’,30,40.5,[1,2]]
A list within another list is nested.
A list that contains no elements is called an empty list; you can create one
with empty brackets [ ].
Example
Cheeses=[‘Cheddar’,’Edam’,’Gouda’]
print(cheeses[0])
Output:
cheddar
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.
Example
numbers=[17,123]
numbers[1]=5
print(numbers)
Output:
[17,5]
The one-eth element of numbers, which used to be 123, is now 5.
We can think of a list as a relationship between indices and elements. This
relationship is called a mapping; each index “maps to” one of the elements.
Lists are represented by boxes with the word “list” outside and the elements
of the list inside. cheeses refers to a list with three elements indexed 0, 1
and 2.
Numbers contains two elements; the diagram shows that the value of the
second element has been reassigned from 123 to 5. empty refers to a list
with no elements.
In Operator
Example
for cheese in cheeses:
print(cheese)
This works well if you only need to read the elements of the list. But if you
want to write or update the elements, you need the indices. A common way to
do that is to combine the functions range and len.
for i in range(len(numbers)):
numbers[i]=[i]*2
This loop traverses the list and updates each element. len returns the
number of elements in the list. range returns a list of indices from 0 to n- 1,
where n is the length of the list.
Each time through the loop i gets the index of the next element. The
assignment statement in the body uses i to read the old value of the element
and to assign the new value.
A for loop over an empty list never executes the body.
Example
for x in []:
print('this never happens')
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,[‘sam’,’hari’,’robert’],[1,2,3]]
Program-1
cheeses=['cheddar','Edam','Gouda']
for cheese in cheeses:
print(cheese)
Output
cheddar
Edam
Gouda
Program-2
numbers=[12,13,14,15]
print(len(numbers))
for i in range(len(numbers)):
numbers[i]=[i]*2
print(numbers)
Output
[[0, 0], [1, 1], [2, 2], [3, 3]]
List Operations
The most conventional method to perform the list concatenation, the use of “+”
operator can easily add the whole of one list behind the other list and hence
perform the concatenation.
Program-1
test_list3 = [1, 4, 5, 6, 5]
test_list4 = [3, 5, 7, 2, 5]
# using + operator to concat
test_list3 = test_list3 + test_list4
# Printing concatenated list
print ("Concatenated list using + : " + str(test_list3))
Output
Concatenated list using + : [1, 4, 5, 6, 5, 3, 5, 7, 2, 5]
Output
[1,2,3,1,2,3,1,2,3]
Nested List
A list can contain any sort object, even another list (sublist), which in turn
can contain sublists themselves, and so on. This is known as nested list.
A nested list is created by placing a comma-separated sequence of sublists.
Example: L = ['a', ['bb', ['ccc', 'ddd'], 'ee', 'ff'], 'g', 'h']
Access individual items in a nested list using multiple indexes.
Access a nested list by negative indexing as well.
Negative indexes count backward from the end of the list. So, L[-1] refers to
the last item, L[-2] is the second-last, and so on.
Program-1
L = ['a', 'b', ['cc', 'dd', ['eee', 'fff']], 'g', 'h']
print(L[2])
print(L[2][2])
print(L[2][2][0])
Output
['cc', 'dd', ['eee', 'fff']]
['eee', 'fff']
eee
Program-2
L = ['a', 'b', ['cc', 'dd', ['eee', 'fff']], 'g', 'h']
print(L[-3])
print(L[-3][-1])
print(L[-3][-1][-2])
Output
['cc', 'dd', ['eee', 'fff']]
['eee', 'fff']
eee
List Slices
To access a range of items in a list, you need to slice a list.
The way to do this is to use the simple slicing operator : With this operator
you can specify where to start the slicing, where to end and specify the step.
If L is a list, the expression L [ start : stop : step ] returns the portion of the
list from index start to index stop, at a step size step.
Syntax:
L[start:stop:step]
Where start means starting position, stop means ending position and step
means increment or decrement.
Since lists are mutable, it is often useful to make a copy before performing
operations that fold, spindle or mutilate lists.
A slice operator on the left side of an assignment can update multiple
elements.
Program-1
L = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
print(L[2:7])
Output
['c', 'd', 'e', 'f', 'g']
Program-2
L = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
print(L[-7:-2])
Output
['c', 'd', 'e', 'f', 'g']
Program-3
L = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
print(L[2:-5])
Output
['c', 'd']
Program-4
L = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
print(L[2:7:2])
Output
['c', 'e', 'g']
Program-5
L = ['a', 'b', 'c', 'd', 'e']
L[1:4] = [1, 2, 3]
print(L)
Output
['a', 1, 2, 3, 'e']
List Methods
1. count() : The count() method returns the number of times the specified
element appears in the list.
Syntax: list.count(element)
Program
vowels = ['a', 'e', 'i', 'o', 'i', 'u']
count = vowels.count('i')
print('The count of i is:', count)
count = vowels.count('p')
print('The count of p is:', count)
Output
The count of i is: 2
The count of p is: 0
2. index() : The index() method returns the index of the specified element in
the list.
Syntax: list.index(element, start, end)
If the element is not found, a ValueError exception is raised.
Program
vowels = ['a', 'e', 'i', 'o', 'i', 'u']
index = vowels.index('e')
print('The index of e:', index)
index = vowels.index('i')
print('The index of i:', index)
Output
The index of e: 1
The index of i: 2
3. remove() : This method is used to remove specified item from the list. If the
item present multiple times then only first occurrence will be removed.
Syntax: list.remove(element)
If the specified item not present in list then we will get ValueError
Program
n=[10,20,10,30]
n.remove(10)
print(n)
Output
[20, 10, 30]
4. pop() : It removes and returns the last element of the list. This is only
function which manipulates list and returns some element
Syntax: list.pop(index)
If the list is empty then pop() raises IndexError. If the list is out of range
when doing pop() raises IndexError
Program
n=[10,20,10,30]
print(n.pop(2))
print(n)
print(n.pop())
Output
10
[10,20,30]
30
Output
Original List: ['Windows', 'macOS', 'Linux']
Updated List: ['Linux', 'macOS', 'Windows']
6. sort() : In list by default insertion order is preserved. If want to sort the
elements of list according to default natural sorting order then we should go for
sort() method.
Syntax: list.sort(key=..., reverse=...)
For numbers default natural sorting order is Ascending Order
For Strings default natural sorting order is Alphabetical Order
To use sort() function, compulsory list should contain only homogeneous
elements. otherwise we will get TypeError
Program
n=[20,5,15,10,0]
n.sort()
print(n)
s=["Dog","Banana","Cat","Apple"]
s.sort()
print(s)
Output
[0, 5, 10, 15, 20]
['Apple', 'Banana', 'Cat', 'Dog']
7. clear() :The clear() method removes all items from the list.
Syntax: list.clear()
Program
n=[20,5,15,10,0]
print(n.clear())
Output
None
8. append() :The append() method adds an item to the end of the list.
Syntax: list.append(item)
Program
animals = ['cat', 'dog', 'rabbit']
animals.append('guinea pig')
print('Updated animals list: ', animals)
Output
Updated animals list: ['cat', 'dog', 'rabbit', 'guinea pig']
9. extend() :The extend() method adds all the elements of an iterable (list,
tuple, string etc.) to the end of the list.
Syntax: list.extend(iterable)
Program
languages = ['French', 'English']
languages1 = ['Spanish', 'Portuguese']
languages.extend(languages1)
print('Languages List:', languages)
Output
Languages List: ['French', 'English', 'Spanish', 'Portuguese']
Deleting Elements
There are several ways to delete elements from a list. The deleting elements
of the methods are are pop, remove and del keyword.
The del keyword is used to delete objects. In Python everything is an object,
so the del keyword can also be used to delete variables, lists, or parts of a
list etc.
Syntax: del obj_name
Program-1
x= ["apple", "banana", "cherry"]
del x[0]
print(x)
Output
[‘banana’, ‘cherry’]
Program-2
x= ["apple", "banana", "cherry"]
del x
print(x)
Output
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
x
NameError: name 'x' is not defined
Output:
[‘s’,’p’,’a’,’m’]
Because list is the name of a built-in function, you should avoid using it as a
variable name. I also avoid l because it looks too much like 1. So that’s why I use
t. The list function breaks a string into individual letters. If you want to break
a string into words, we can use the split method.
Output:
[‘learning’,’python’, ‘is’, ‘easy’]
Output:
Spam-spam-spam
a=‘banana’
b=‘banana’
We know that a and b both refer to a string, but we don’t know whether they
refer to the same string. There are two possible states.
In one case, a and b refer to two different objects that have the same value.
In the second case, they refer to the same object. To check whether two
variables refer to the same object, you can use the is operator
In this example, Python only created one string object, and both a and b
refer to it.
a=‘banana’
b=‘banana’
a is b
Output:
True
But when you create two lists, you get two objects
A=[1,2,3]
B=[1,2,3]
A is B
Output:
False
In this case we would say that the two lists are equivalent, because they have
the same elements, but not identical, because they are not the same object.
If two objects are identical, they are also equivalent, but if they are
equivalent, they are not necessarily identical.
Until now, we have been using “object” and “value” interchangeably, but it is
more precise to say that an object has a value.
If you execute [1,2,3], we get a list object whose value is a sequence of
integers. If another list has the same elements, we say it has the same value,
but it is not the same object.
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
Output:
True
The association of a variable with an object is called a reference. In this
example, there are two references to the same object.
An object with more than one reference has more than one name, so we say
that the object is aliased.
If the aliased object is mutable, changes made with one alias affect the
other.
b[0]=17
print(a)
Although this behavior can be useful, it is error-prone. In general, it is safer
to avoid aliasing when you are working with mutable objects.
a=“banana”
b=“banana”
It almost never makes a difference whether a and b refer to the same string
or not.
List Arguments
When you pass a list to a function, the function gets a reference to the list.
If the function modifies a list parameter, the caller sees the change. For
example, delete_head removes the first element from a list.
Program
def delete_head(t):
del t[0]
letters=[‘a’,’b’,’c’]
delete_head(letters)
print(letters)
Output
['b', 'c']
The parameter t and the variable letters are aliases for the same object.
Since the list is shared by two frames, I drew it between them.
It is important to distinguish between operations that modify lists and
operations that create new lists. For example, the append method modifies a
list, but the + operator creates a new list.
Program
t=[1,2]
t1=t.append(3)
print(t)
t2=t+[4]
print(t2)
Output
[1, 2, 3]
[1, 2, 3, 4]
This difference is important when you write functions that are supposed to
modify lists. For example, this function does not delete the head of a list.
def bad_delete_head(t):
t=t[1:] #wrong
The slice operator creates a new list and the assignment makes t refer to it,
but none of that has any effect on the list that was passed as an argument.
An alternative is to write a function that creates and returns a new list. For
example, tail returns all but the first element of a list:
def tail(t):
return t[1:]
This function leaves the original list unmodified. Here’s how it is used.
Program
def tail(t):
return t[1:]
letters=['a','b','c']
rest=tail(letters)
print(rest)
Output
['b', 'c']
Tuple:
A tuple is same as list, except that the set of elements is enclosed in
parentheses instead of square brackets.
A tuple is an immutable list. i.e. once a tuple has been created, you can't add
elements to a tuple or remove elements from the tuple.
But tuple can be converted into list and list can be converted in to tuple.
Benefit of Tuple:
Operations on Tuples:
1. Indexing
2. Slicing
3. Concatenation
4. Repetitions
5. Membership
6. Comparison
Tuple methods:
Tuple is immutable so changes cannot be done on the elements of a tuple once it
is assigned.
Tuple Assignment:
>>>(a,b,c)=(1,2,3)
>>>print(a)
1
>>>print(b)
2
>>>print(c)
3
Example1:
def div(a,b):
r=a%b
q=a//b
return(r,q)
a=eval(input("enter a value:"))
b=eval(input("enter b value:"))
r,q=div(a,b)
print("reminder:",r)
print("quotient:",q)
Output:
enter a value:4
enter b value:3
reminder: 1
quotient: 1
Example2:
def min_max(a):
small=min(a)
big=max(a)
return(small,big)
a=[1,2,3,4,6]
small,big=min_max(a)
print("smallest:",small)
print("biggest:",big)
Output:
smallest: 1
biggest: 6
Tuple as argument:
The parameter name that begins with * gathers argument into a tuple.
Example:
def printall(*args):
print(args)
printall(2,3,'a')
Output:
(2, 3, 'a')
Set
A set is a mutable collection of distinct hashable objects, same as
the list and tuple. It is an unordered collection of objects, meaning it does not
record element position or order of insertion and so cannot access elements
using indexes.
Set Operations
Various set operations can be performed. Operators |, &, - and ^ perform
union, intersection, difference, and symmetric difference operations,
respectively. Each of these operators has a corresponding method associated
with the built-in set class.
Operation Example
Union: Returns a new set with elements from >>> s1={1,2,3,4,5}
both the sets. >>> s2={4,5,6,7,8}
>>> s1|s2
Operator: | {1, 2, 3, 4, 5, 6, 7, 8}
Method: set.union() >>> s1={1,2,3,4,5}
>>> s2={4,5,6,7,8}
>>> s1.union(s2)
{1, 2, 3, 4, 5, 6, 7, 8}
>>> s2.union(s1)
{1, 2, 3, 4, 5, 6, 7, 8}
Intersection: Returns a new set containing >>> s1={1,2,3,4,5}
elements common to both sets. >>> s2={4,5,6,7,8}
>>> s1&s2
Operator: & {4, 5}
Method: set.intersection() >>> s2&s1
{4, 5}
Operation Example
>>> s1={1,2,3,4,5}
>>> s2={4,5,6,7,8}
>>> s1.intersection(s2)
{4, 5}
>>> s2.intersection(s1)
{4, 5}
Difference: Returns a set containing elements >>> s1={1,2,3,4,5}
only in the first set, but not in the second set. >>> s2={4,5,6,7,8}
>>> s1-s2
Operator: - {1, 2, 3}
Method: set.difference() >>> s2-s1
{8, 6, 7}
>>> s1={1,2,3,4,5}
>>> s2={4,5,6,7,8}
>>> s1.difference(s2)
{1, 2, 3}
>>> s2.difference(s1)
{8, 6, 7}
Symmetric Difference: Returns a set >>> s1={1,2,3,4,5}
consisting of elements in both sets, excluding >>> s2={4,5,6,7,8}
the common elements. >>> s1^s2
{1, 2, 3, 6, 7, 8}
Operator: ^ >>> s2^s1
Method: set.symmetric_difference() {1, 2, 3, 6, 7, 8}
>>> s1={1,2,3,4,5}
>>> s2={4,5,6,7,8}
>>> s1.symmetric_difference(s2)
{1, 2, 3, 6, 7, 8}
>>> s2.symmetric_difference(s1)
{1, 2, 3, 6, 7, 8}
Set Methods
The following table lists built-in set methods:
Method Description Example
set.add() Adds an element to the set. If an lang = {'Python', 'C++',
element is already exist in the set, 'Java', 'C'}
lang.add('Go')
then it does not add that element.
print(lang)
cities.pop()
Method Description Example
set.remove() Removes the specified element cities =
from the set. If the specified {'Delhi','Chicago','New
York'}
element not found, raise an error.
cities.remove('Delhi')
print(cities)
set.update() Updates the set by adding distinct nums = { 1, 2, 3 }
elements from the passed one or evenNums = { 2, 4, 6 }
primeNums = { 5, 7 }
more iterables.
nums.update(evenNums,
primeNums)
Dictionaries
Dictionary is an unordered collection of elements. An element in dictionary
has a key: value pair.
All elements in dictionary are placed inside the curly braces i.e. { }
Elements in Dictionaries are accessed via keys and not by their position.
The values of a dictionary can be any data type.
Keys must be immutable data type (numbers, strings, tuple)
Operations on dictionary:
1. Accessing an element 2. Update
3. Add element 4. Membership
Methods in dictionary:
Difference between List, Tuples and dictionary:
Map function
The map() function applies a given function to each item of an iterable (list,
tuple etc.) and returns a list of the results.
Syntax: map(function, iterable, ...)
The returned value from map() (map object) can then be passed to functions
like list() (to create a list), set() (to create a set) and so on.
Program
def myfunc(a, b):
return a+b
x = map(myfunc, ('apple', 'banana', 'cherry'), ('orange', 'lemon', '
pineapple'))
#convert the map into a list, for readability:
print(list(x))
Output
['appleorange', 'bananalemon', 'cherrypineapple']
Reduce function
An operation like that combines a sequence of elements into a single value is
sometimes called reduces.
Syntax: reduce(function,sequence[,initial])
The reduce() function accepts a function and a sequence and returns a single
value calculated as follows:
Initially, the function is called with the first two items from the sequence
and the result is returned.
The function is then called again with the result obtained in step 1 and the
next value in the sequence. This process keeps repeating until there are items
in the sequence.
Program
Import functools
def do_sum(x1, x2):
return x1 + x2
result=functools.reduce(do_sum, [1, 2, 3, 4])
print(result)
Output
10
Filter Functions
The filter() method filters the given sequence with the help of a function
that tests each element in the sequence to be true or not.
Syntax: filter(function, iterable(s))
filter() method returns an iterator that passed the function check for each
element in the iterable.
filter() method is equivalent to:
1. # when function is defined (element for element in iterable if
function(element))
2. # when function is None (element for element in iterable if element)
Program
letters = ['a', 'b', 'd', 'e', 'i', 'j', 'o']
def filterVowels(letter):
vowels = ['a', 'e', 'i', 'o', 'u']
if(letter in vowels):
return True
else:
return False
filteredVowels = filter(filterVowels, letters)
print('The filtered vowels are:')
for vowel in filteredVowels:
print(vowel)
Output
The filtered vowels are:
a
e
i
o
Output :
[1, 'Yash', ['a', 'e']]
The first element is an integer, the second a string and the third is an list of
characters.
Array:
An array is a vector containing homogeneous elements i.e. belonging to the
same data type. Elements are allocated with contiguous memory locations
allowing easy modification, that is, addition, deletion, accessing of elements. In
Python, we have to use the array module to declare arrays. If the elements of
an array belong to different data types, an exception “Incompatible data
types” is thrown.
import array
sample_array = array.array('i', [1, 2, 3])
# accessing elements of array
for i in sample_array:
print(i)
Output:
1
2
3
List Array
The entire list can be printed without A loop has to be formed to print or
any explicit looping access the components of array