Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
3 views

Python Module 3

Module 3 covers fundamental data structures in Python, including strings, lists, tuples, dictionaries, and sets, along with their operations and methods. It explains string indexing, slicing, immutability, and various string methods such as find, replace, and split. Additionally, the module discusses traversing strings using loops and counting occurrences of characters.

Uploaded by

Arjun Sinha
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Python Module 3

Module 3 covers fundamental data structures in Python, including strings, lists, tuples, dictionaries, and sets, along with their operations and methods. It explains string indexing, slicing, immutability, and various string methods such as find, replace, and split. Additionally, the module discusses traversing strings using loops and counting occurrences of characters.

Uploaded by

Arjun Sinha
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 42

MODULE – 3(Strings, Lists, Tuples, Dictionaries and Sets)

Strings, Lists, Tuples, Dictionaries and Sets: Strings-Operations, Slicing,


Methods, List-Operations, Slicing, Methods, Tuple- Operations, Methods,
Sets-Operations, Methods, Dictionaries- Operations, Methods, Mutable
Vs Immutable, Arrays Vs Lists, Map, Reduce, Filter, Comprehensions.

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

 So b is the 0th letter (“zero-eth”) of ‘banana’, a is the 1th letter (“one-


eth”), and n is the 2th (“two-eth”) letter.
 We can use any expression, including variables and operators, as an
index, but the value of the index has to be an integer. Otherwise you get:

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'

Traversal with a loops


 A lot of computations involve processing a string one character at a time.
Often they start at the beginning, select each character in turn, do
something to it, and continue until the end. This pattern of processing is
called a traversal. The ways to write a traversal is with a for loop and
while loop.

 This loop traverses the string and displays each letter on a line by itself.

 The loop condition is index<len(fruit), so when index is equal to the


length of the string, the condition is false, and the body of the loop is not
executed.

 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.

 The following example shows how to use concatenation (string addition)


and a for loop to generate an abecedarian series (that is, in alphabetical
order).
 In Robert McCloskey’s book Make Way for Ducklings, the names of the
ducklings are Jack, Kack, Lack, Mack, Nack, Ouack, Pack, and Quack. This
loop outputs these names in order.

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

Strings are Immutable:


 It can be use the [] operator on the left side of an assignment, with the
intention of changing a character in a string.

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 word[index]==lettter, the function breaks out of the loop and returns


immediately.

 If the character doesn’t appear in the string, the program exits the loop
normally and returns -1

 This pattern of computation—traversing a sequence and returning when


we find what we are looking for—is called a search.

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.

 A method call is called an invocation; in this case, we would say that we


are invoking upper on the word.

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)

 It will always search from begin index to end-1 index


Syntax:
s.find(substring,begin,end)
Program-1
s='Learning Python is very easy'
print(s.find("Python"))
print(s.find("Java"))
print(s.find("r"))
print(s.rfind("r"))
Output
9
-1
3
21

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

5. Counting substring in the given String:


 We can find the number of occurrences of substring present in the given
string by using count() method.

s.count(substring) ==> It will search through out the string


s.count(substring, begin, end) ===> It will search from begin index
to end-1 index
program
s="abcabcabcabcadda"
print(s.count('a'))
print(s.count('ab'))
print(s.count('a',3,7))

Output
6
4
2

6. Replacing a string with another string


 The replace() method returns a copy of the string where all occurrences
of a substring is replaced with another substring.
Syntax:
string.replace(oldvalue, newvalue, count)
 Once we creates string object, we cannot change the content.
 This non changeable behavior is nothing but immutability.
 If we are trying to change the content by using any method, then with
those changes a new object will be created and changes won't be
happened in existing object.
 Hence with replace() method also a new object got created but existing
object won't be changed.

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

9. Changing case of a String:


We can change case of a string by using the following 5 methods.
1. upper() - To convert all characters to upper case
Syntax: string.upper()
2. lower() - To convert all characters to lower case
Syntax: string.lower()
3. swapcase() - converts all lower case characters to upper case and all
upper case characters to lower case
Syntax: string.swapcase()
4. title() - To convert all character to title case. i.e first character in
every word should be upper case and all remaining characters
should be in lower case.
Syntax: string.title()
5. capitalize() - Only first character will be converted to upper case
and all remaining characters can be converted to lower case
Syntax: string.capitalize()

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

10. To check type of characters present in a string


Python contains the following methods for this purpose.
1. isalnum() : Returns True if all characters are alphanumeric( a to z , A
to Z ,0 to9 )
Syntax: string.isalnum()
2. isalpha() : Returns True if all characters are only alphabet symbols(a
to z,A to Z)
Syntax: string.isalpha()
3. isdigit() : Returns True if all characters are digits only( 0 to 9).
Syntax: string.isdigit()
4. islower() : Returns True if all characters are lower case alphabet
symbols.
Syntax: string.islower()
5. isupper() : Returns True if all characters are upper case alphabet
symbols
Syntax: string.isupper()
6. istitle() : Returns True if string is in title case.
Syntax: string.istitle()
7. isspace() : Returns True if string contains only spaces
Syntax: string.isspace()

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.

 A common way to address this problem is to convert strings to a standard


format, such as all lowercase, before performing the comparison. Keep
that in mind in case you have to defend yourself against a man armed with
a Pineapple.

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 [ ].

Note: In the above example put the brackets to print function

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.

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.

List indices work the same way as string indices:


 Any integer expression can be used as an index.
 If you try to read or write an element that does not exist, we can get an
index error
 If an index has a negative value, it counts backward from the end of the list.

In Operator

The ‘in’ operator is used to check if a value exists in a sequence or not.


Evaluates to true if it finds a variable in the specified sequence and false
otherwise
Traversing a list:
 The most common way to traverse the elements of a list is with a for loop.
The syntax is the same as for strings.

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]

Sequences datatypes (both mutable and immutable) support a repetition


operator *. The repetition operator * will make multiple copies of that
particular object and combines them together. When * is used with an integer it
performs multiplication but with list, tuple or strings it performs a repetition
Program-2
l1= [1,2,3]
print(l1*3)

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

5. reverse(): The reverse() method reverses the elements of the list.


Syntax: list.reverse()
Program
systems = ['Windows', 'macOS', 'Linux']
print('Original List:', systems)
systems.reverse()
print('Updated List:', systems)

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

List and Strings


A string is a sequence of characters and a list is a sequence of values, but a list
of characters is not the same as a string. To convert from a string to a list of
characters, we can use list.
s='spam'
t=list(s)
print(t)

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.

s='learning python is easy'


print(s.split())

Output:
[‘learning’,’python’, ‘is’, ‘easy’]

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='-'
s.split(delimiter)
print(s)

Output:
Spam-spam-spam

Objects and Values


 If we execute these assignment statements:

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.

 For immutable objects like strings, aliasing is not as much of a problem. In


this example:

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:

 Tuples are faster than lists.


 If the user wants to protect the data from accidental changes, tuple can be
used.
 Tuples can be used as keys in dictionaries, while lists can't.

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:

 Tuple assignment allows, variables on the left of an assignment operator and


values of tuple on the right of the assignment operator.
 Multiple assignment works by creating a tuple of expressions from the right
hand side, and a tuple of targets from the left, and then matching each
expression to a target.
 Because multiple assignments use tuples to work, it is often termed
tuple assignment.

Uses of Tuple assignment:


It is often useful to swap the values of two variables.
Example:
Swapping using temporary variable:
a=20
b=50
temp = a
a = b
b = temp
print("value after swapping is",a,b)

Swapping using tuple assignment:


a=20
b=50
(a,b)=(b,a)
print("value after swapping is",a,b)
Multiple assignments:
Multiple values can be assigned to multiple variables using tuple assignment.

>>>(a,b,c)=(1,2,3)
>>>print(a)
1
>>>print(b)
2
>>>print(c)
3

Tuple as return value:

 A Tuple is a comma separated sequence of items.


 It is created with or without ( ).
 A function can return one value. if you want to return more than one value
from a function. we can use tuple as return value.

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)

set.clear() Removes all the elements from the lang.clear()


set.
Method Description Example
set.copy() Returns a shallow copy of the set. langs =
{'Python','C++','Java'}
copiedLangs = langs.copy()
print("Original Set: ",
langs)
print("Copied Set: ",
copiedLangs)

set.difference_update() Updates the set on which the empids = {1,2,3,4,5}


method is called with the elements mgrids = {1,2,3}
empids.difference_update(m
that are common in another set
grids)
passed as an argument. print("empids: ", empids)
print("mgrids: ", mgrids)

set.discard() Removes a specific element from langs =


the set. {'Python','Go','C++','Java
'}
langs.discard('C++')

set.intersection_update() Updates the set on which the nums = {1, 2, 3, 4, 5 }


instersection_update() method is oddNums = {1, 3, 5, 7, 9}
nums.intersection_update(o
called, with common elements
ddNums)
among the specified sets. print(nums)
set.isdisjoint() Returns true if the given sets have nums = {1, 2, 3, 4, 5 }
no common elements. Sets are oddNums = {1, 3, 5, 7, 9}
primeNums = {7, 11, 13}
disjoint if and only if their
intersection is the empty set. print(nums.isdisjoint(oddN
ums))
print(nums.isdisjoint(prim
eNums))
set.issubset() Returns true if the set (on which nums = {1, 2, 3, 4, 5 }
the issubset() is called) contains oddNums = {1, 3, 5}
primeNums = {1, 3, 5, 7}
every element of the other set
passed as an argument. print(oddNums.issubset(num
s))
print(primeNums.issubset(n
ums))
set.pop() Removes and returns a random cities =
element from the set. {'Mumbai','Chicago','New
York'}

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)

print("Updated set: ",


nums)

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.

 In Python2, reduce() was a built-in function. However, in Python 3, it is moved


to functional module.

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

Advanced list processing:


List Comprehension:
 List comprehensions provide a concise way to apply operations on a list.
 It creates a new list in which each element is the result of applying a given
operation in a list.
 It consists of brackets containing an expression followed by a “for” clause,
then a list.
 The list comprehension always returns a result list.

Syntax: list = [ expression for item in list if conditional ]


List Vs Array
List:
A list in Python is a collection of items which can contain elements of multiple
data types, which may be numeric, character logical values, etc. It is an
ordered collection supporting negative indexing. A list can be created using []
containing data values.
Contents of lists can be easily merged and copied using python’s inbuilt
functions.

# creating a list containing elements


# belonging to different data types
sample_list = [1,"Yash",['a','e']]
print(sample_list)

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

Differences between List and Array in Python:

List Array

Can consist of elements belonging to Only consists of elements belonging


different data types to the same data type

No need to explicitly import a module Need to explicitly import a module


for declaration for declaration

Cannot directly handle arithmetic Can directly handle arithmetic


operations operations

Can be nested to contain different Must contain either all nested


type of elements elements of same size

Preferred for shorter sequence of Preferred for longer sequence of


data items data items

Greater flexibility allows easy


Less flexibility since addition,
modification (addition, deletion) of
deletion has to be done element wise
data

The entire list can be printed without A loop has to be formed to print or
any explicit looping access the components of array

Consume larger memory for easy Comparatively more compact in


addition of elements memory size

You might also like