[go: up one dir, main page]

100% found this document useful (1 vote)
19 views90 pages

Unit -II String, Lists, Dict, Tuple, Sets

The document covers fundamental concepts of strings and lists in Python, including creation, basic operations, methods, and formatting. It explains string manipulation techniques such as slicing, concatenation, and searching, as well as list operations like indexing, slicing, and built-in functions. Additionally, it highlights the immutability of strings and provides examples for better understanding.

Uploaded by

Saraswathi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
19 views90 pages

Unit -II String, Lists, Dict, Tuple, Sets

The document covers fundamental concepts of strings and lists in Python, including creation, basic operations, methods, and formatting. It explains string manipulation techniques such as slicing, concatenation, and searching, as well as list operations like indexing, slicing, and built-in functions. Additionally, it highlights the immutability of strings and provides examples for better understanding.

Uploaded by

Saraswathi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 90

Unit II

BCA 4rth Semester


 Strings
 Creating and Storing Strings,
 Basic String Operations,
 Accessing Characters in String by Index Number,
 String Slicing and Joining,
 String Methods,
 Formatting Strings,
 Lists
 Creating Lists,
 Basic List Operations,
 Indexing and Slicing in Lists,
 Built-In Functions Used on Lists,
 List Methods
 Sets, Tuples and Dictionaries.
Strings
A string consists of a sequence of characters, which includes
letters, numbers, punctuation marks and spaces.
 Creating and Storing Strings :
 Created by enclosing text in single and double quotes.
 Triple quote can be used for multi-line strings.
>>> S='hello'
>>> Str="hello"
>>> M="""This is a multiline String across two lines""“
 contains backslash and don't want it to be treated as an escape
character, called raw string. Is created by prefixing a string
literal with 'r' or 'R‘.
>>> s= r" world health \n organization"
>>> print(s)
world health \n organization
 Basic String Operations
 Concatenation can be done:
 using + operator : str3 = str1 + str2
 placing strings side by side : str= 'this' 'is' 'python' 'class'
 The in operator :
 Is a Boolean operator which takes two string operands.
 Ex: if 'pa' in “roopa:
 Ex: if ';' not in “roopa”:
 Ex:3 we can avoid writing longer codes like this
if t=='a' or t=='e' or t=='i' or t=='o' or t=='u':
instead we can write this code with ‘in’ operator
if t in 'aeiou‘:
 String comparison
 < (less than), > (greater than), == (equals) etc
 Results in a Boolean value True or False
 Comparison happens using ASCII codes
Ex:2
if word < ' Ravindra':
print('Your name,' + word + ', comes before Ravindra.’)
elif word > ' Ravindra':
print('Your name,' + word + ', comes after Ravindra.’)
else:
print('All right, Ravindra.')
 Traversal through a string with a loop
 Extracting every character of a string one at a time
 Performing some action on that character
 while loop
 for loop

 Accessing Characters in String by Index Number


 single character in a string using an index
specified in []
 integer and starts at zero
word = 'Python'
>>> word[0] # character in position 0
'P‘
 negative indexing of string starting from the end of the string


 String Slicing and Joining
 String slices :
 A segment or a portion of a string is called as slice
 extracted from a string using colon (:)
 The basic syntax for slicing a string :

String_name[start : end : step]


Where,
start : the position from where it starts
end : the position where it ends
step: Is used to indicate num of steps
to be incremented.Default is 1.
String Method
capitalize() Converts the first character of the string to a capital
(uppercase) letter
find() Returns the lowest index of the substring if it is found
strip() Returns the string with both leading and trailing characters
lstrip() Returns the string with leading characters removed
rstrip() Removes trailing characters
casefold() Implements caseless string matching
startswith() Returns “True” if a string starts with the given prefix
endswith() Returns “True” if a string ends with the given suffix
lower() Converts all uppercase characters in a string into
lowercase
upper() Converts all lowercase characters in a string into
uppercase
join() Returns a concatenated String
count() Returns the number of occurrences of a substring in the
string.
 String Methods
 capitalize() : print(msg.capitalize())
 find() : s.find(sub[, start[, end]]) -> int
print(st.find(‘x’))
 strip() : print(st.strip())
 strip(chars) : print(st.strip(‘#’))
 rstrip() : remove whitespace at right side
 lstrip() : remove whitespace at left side
 casefold() : caseless comparisons
 split(“separator”) : s="a,b,c,d,e”print(s.split(",")) [‘a', ‘b', ‘c', ‘d‘, ’e’]
 startswith(prefix, start, end) : print(str.startswith("L"))False
 join() : Concatenate.
 lower(),upper(),replace(x,y)
 count(x),index(x)
 isalpha()
 Formatting Strings
 format operator : “%d” to format an integer, “%g” to format a
floating point number and “%s” to format a string:
 f-string :
 prefixed with “f”,
 Replacement fields, which are expressions enclosed within curly
braces {}.
a=10
print(f”the value is {a}”)
the value is 10
 format( ) function :
 positional_argument : print("{0} college{1}
".format("SDIT",“MCA"))
 keyword_argument: print(“MCA department {0} ‘D’.format("6",
college=“SDIT"))
strings
 A string is a sequence of characters.
 For example, the English language has 26 characters.
 Computers do not deal with characters, they deal with
numbers (binary).
 This conversion of character to a number is called
encoding
 the reverse process is decoding
example
#checking data type
string='hello'
type(string)
--------------
Output:
str
Example:reading string from user
#reading string
string=input("enter the string")
print(string)
------
enter the string good morning have a nice day good
morning have a nice day
Traversal with a for loop
 Accessing character(s)
 Example:

#traversal with for loop


message='hello!'
index=0
for i in message:
print("message[",index,"]=",i)
index+=1
output
message[ 0 ]= h
message[ 1 ]= e
message[ 2 ]= l
message[ 3 ]= l
message[ 4 ]= o
message[ 5 ]= !
String Slicing in Python
example
#slicing example
snack = "Chocolate cookie."
print(snack[0])
print(snack[9])
print(snack[-1])
-------------------
#slicing example
snack = "Chocolate cookie."
print(snack[4])
print(snack[9])
print(snack[-2])
String slices
 A segment of string is called a slice
 Just like selecting character

The syntax for range slicing is the following:

[Start index (included): Stop index (excluded)]

Ex1:
#string slice
s='hello python'
s[0:7]
Output:
'hello p'
Continue.
#slice2
fruit='banana'
fruit[:3]
Output:
'ban‘
---------------------
Continue..
#slice3
fruit='banana'
fruit[3:]
Output:
'ana‘
-----
#slice3
fruit='banana'
fruit[3:3]
Output: ‘’
Strings are immutable
 Once strings are created cant be changed.
String concatenating
 Joining together
 + operator
 Example:
#string concatenation
str1='hello'
str2='python'
str3=str1+str2
print("the concatenated string is:",str3)
Output:
the concatenated string is: hellopython
example2
#concat 2 strings
string1 = input("enter the first string")
string2 = input("enter the second string“)
full_name = string1 + " " + string2
print(full_name)
example3
#error_example
cost = 15
string1 = "The total in Euro is: “
bill = string1 + cost
print(bill)
Error message
 TypeError Traceback (most recent call last)
<ipython-input-6-bdea940ccf25>
in <module> 2
string1 = "The total in Euro is: "
bill = string1 + cost
print(bill)
TypeError: can only concatenate str (not "int") to str
correction
#correct code
cost = 15
string1 = "The total in Euro is:”
bill = string1 + str(cost)
print(bill)
----------------
Output:
The total in Euro is: 15
String append
 Add something at the end.
 += operator used

#program to append string


str="hello\t"
name=input("enter your name:")
str+=name
str+=".welcome to python programming."
print(str)
Output:
enter your name:abhishek
hello abhishek.welcome to python programming.
Multiply() in strings
 * operator: used for reapeat string n number of times.
 Example:
#dot operator in string
str='hello'
print(str * 3)
output:
hellohellohello
Searching
 It takes a character and finds the index where that
character appear.
 If character not found , the function returns -1.
 Traversing a sequence and returning
Looping and counting
#example looping with counting
word ='banana'
count=0
for letter in word :
if letter == 'a':
count=count+1
print(count)
String methods
 Performs variety of useful operations.
 Similar to functions
 Takes arguments and returns a value

upper():
word. upper()
example
#coverting upper case
word='banana'
new_word=word.upper()
print(new_word)
Output:
BANANA
find()
#coverting upper case
word='banana'
index=word.find('n')
print(index)
Output:
2
Built in functiuons
 str.capitalize():
returns a copy of the string with its first
character capitalized.

Example:
str.capitalize('cookie')
Cookie
str.islower():
 returns true if all characters in the string are
lowercase, false otherwise.

 Example:
snack = 'cookie'
snack.islower()
Method Description
Converts the first character
capitalize()
to upper case
center() Returns a centered string
Returns the number of times
count() a specified value occurs in a
string
Returns an encoded version
encode()
of the string
Method Description
Adds an element at the end of
append()
the list
Removes all the elements from
clear()
the list
copy() Returns a copy of the list
Returns the number of elements
count()
with the specified value
Add the elements of a list (or
extend() any iterable), to the end of the
current list
Returns the index of the first
index()
element with the specified value
Adds an element at the specified
insert()
position
Removes the element at the
pop()
specified position
Removes the first item with the
remove()
specified value
#remove punctuation
# define punctuation
punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~'''

my_str = "Hello!!!, he said ---and went."

# remove punctuation from the string


no_punct = ""
for char in my_str:
if char not in punctuations:
no_punct = no_punct + char

# display the unpunctuated string


print(no_punct)
example
# define punctuation
punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~'''

#To take input from the user


my_str = input("Enter a string: ")

# remove punctuation from the string


no_punct = ""
for char in my_str:
if char not in punctuations:
no_punct = no_punct + char

# display the unpunctuated string


print(no_punct)
Lists
 A lists is a sequence
 An ordered sequence of values
 It is a data structure in Python
 Values can be of any type: integer, float,
strings, lists, tuples, dictionaries..
 enclosed within square brackets.
 Creating Lists
 Basic List Operations : + *
 List Aliasing : == , is
 Indexing and Slicing in Lists :
 Built In Functions
 List Methods
 Creating Lists:
 L = [1,2,3]//square brackets to indicate the start and end of the list,
separate by comma.
 a = [ ] //Empty list,
 l=list()
 Long list can split it across several lines
nums = [0, 1, 2, 3, 4, 5,
6, 7, 8, 9, 10,11]
 eval(input( )) L = eval(input('Enter a list: ')) // Enter a list: [5,7,9]
 list and range function : num=list(range(10))
 Nested lists : a = ['a', 'b', 'c'] n = [1, 2, 3] x = [a, n] ||
col=[23,[9.3,11.2,],[‘good’], []]
 Basic List Operations
 The plus (+) operator concatenates
 a = a + [1, 3, 5] reassigns a to the new list [10,
20, 30, 1, 3, 5].
 a += [10] updates a to be the new list [10, 20, 30,
1, 3, 5, 10].
 the * operator repeats a list a given number of
times
 print([1, 2, 3] * 3) // [1, 2, 3, 1, 2, 3, 1, 2, 3]
 List Aliasing
 both of them will refer to same object in the memory
 The association of a variable with an object is called as
reference.
a = [10, 20, 30, 40]
b = [10, 20, 30, 40]
print('Is ', a, ' equal to ', b, '?', sep='', end=' ')
print(a == b)
print('Are ', a, ' and ', b, ' aliases?', sep='', end=' ')
print(a is b)

c = [100, 200, 300, 400] Output:


d = c # creating alias Is [10, 20, 30, 40] equal to [10, 20, 30, 40]?
True
print('Is ', c, ' equal to ', d, '?', Are [10, 20, 30, 40] and [10, 20, 30, 40]
sep='', end=' ') aliases? False
print(c == d) Is [100, 200, 300, 400] equal to [100, 200,
print('Are ', c, ' and ', d, ' aliases?', 300, 400]? True
Are [100, 200, 300, 400] and [100, 200, 300,
sep='', end=' ')
400] aliases? True
print(c is d)
Indexing and Slicing in Lists
 Indexing
 The syntax for accessing the elements of a list using the bracket operator.
 Accessing elements with negative index
 Accessing the elements within inner list can be done by double-indexing
ls=[[1,2],['EC','CS']] //Output : EC
print(ls[1][0])

 List slicing
 Expression : list [ begin : end : step ]
 Begin : defaults to 0, end : defaults to the length of the list, step: default is 1.
 Left side of an assignment can update multiple elements
t = ['a','b','c','d','e','f']
t[1:3] = ['x', 'y']
print(t) //['a', 'x', 'y', 'd', 'e', 'f']

lst =[10,20,30,40,50,60,70,80,90,100]
print(lst) print(lst[:])
print(lst[0:3]) print(lst[-100:3])
print(lst[4:8]) print(lst[4:100])
print(lst[2:5]) print(lst[2:-2:2])
print(lst[-5:-3]) print(lst[::2])
print(lst[:3])
print(lst[4:])
 Built In Functions:
 Len : returns the number of items in the list
 Sum : returns the sum of the items in the list
 Min : returns the minimum of the items in the list
 Max : returns the maximum of the items in the list
List Methods
 append : adds a single item to the existing list
 extend : takes a single argument (a list) and adds it to the end.
 Count : returns the number of times a given element appears in the list
 Insert : new element before the element at a given index. Modifies
//ls.insert(1,"hi")
 index : Returns the lowest index
 Reverse : reverses the elements in the list. Modifies.
 Sort : ascending order. Modifies
 Clear : removes all the elements, list empty
 Deleting Elements: several ways to delete elements
 pop() : removes the item at specified index p and returns its value
 remove():if the index of the element is not known, then the value to be removed can be
specified, will not return the value
 del : when more than one item to be deleted at a time || del my_list[1:5]
Sets
 Python provides a data structure that represents a
mathematical set
 we use curly braces { }
 Are unordered and may contain no duplicate
elements
 Duplicate elements appear only once in the set
 The expression { } does not represent the empty
set.
 Set must contain at least one element.
Creation of sets
>>> s = {10, 3, 7, 2, 11}
>>> s {2, 11, 3, 10, 7}
>>> t = {5, 4, 5, 2, 4, 9}
>>> t {9, 2, 4, 5}

s={10,20,30,40}
s={10,20,2.3,”abc”}
s={10,20,30,20,10,20,10}
s[1] //We cannot access element using index
s={10,20}
s.add(30)
print(s)
s.discard(20)
print(s)
List conversion using set()
>>> l = [10, 13, 10, 5, 6, 13, 2, 10, 5]
>>> s = set(l)
>>> s
{10, 2, 13, 5, 6}

 The element ordering is not preserved, and


duplicate elements appear only once in the set.
Basic operations using set
Cont.
 Python reserves the { } notation for empty
dictionaries
 Python supports the standard mathematical set
operations of intersection, union, set difference, and
symmetric difference.
>>> S = {2, 5, 7, 8, 9, 12}
>>> T = {1, 5, 6, 7, 11, 12}
>>> S | T {1, 2, 5, 6, 7, 8, 9, 11, 12}
>>> S & T {12, 5, 7}
>>> 7 in S True
>>> 11 in S False
Tuples
 A tuple is a collection of heterogeneous elements
 Tuples are written with round brackets.
 Tuple items are ordered, unchangeable, and allow
duplicate values.
 The values stored in a tuple can be any type, and
they are indexed by integers
 A tuple is an immutable list of values
Cont.
 Creation :
 Many ways to a tuple:
 Accessing Elements in a Tuple
 Tuples are immutable
 Comparing tuples
 Tuple assignment
example
#example for tuples
thistuple = ("apple", "banana", "cherry")
print(thistuple)
---------------------
output:
('apple', 'banana', 'cherry')

Allow Duplicates in tuples
• tuples are indexed
• they can have items with the same value

program:
#duplicated allows
thistuple = ("apple", "banana", "cherry", "apple",
"cherry")
print(thistuple)
('apple', 'banana', 'cherry', 'apple', 'cherry')
Tuple Length
#Print the number of items in the tuple
thistuple = ("apple", "banana", "cherry")
print("the length of given tuple :",len(thistuple))
-----------------------
output:
the length of given tuple is: 3
data type of tuples
#checking data type
thistuple = ("apple",)
print(type(thistuple))
----------------------------
<class 'tuple'>
not a tuple
#NOT a tuple
thistuple = ("apple")
print(type(thistuple))
---------------------------
output:
<class 'str'>
example
#example String, int and boolean data types:
tuple1 = ("apple", "banana", "cherry")
tuple2 = (1, 5, 7, 9, 3)
tuple3 = (True, False, False)
print(tuple1)
Output:
print(tuple2)
print(tuple3) ('apple', 'banana', 'cherry')
(1, 5, 7, 9, 3)
(True, False, False)
slice in tuple
#use of slice operation in tuple
tup1=(1,2,3,4,5,6,7,8,9,10)
print("tup1[3:6]=",tup1[3:6])
print("tup1[:8]=",tup1[:8])
print("tup1[4:]=",tup1[4:]) Output:
print("tup1[:]=",tup1[:]) tup1[3:6]= (4, 5, 6)
tup1[:8]= (1, 2, 3, 4, 5, 6, 7, 8)
tup1[4:]= (5, 6, 7, 8, 9, 10)
tup1[:]= (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
updating tuple
 only extract values from a tuple to form another tuple.

#program to extract values from a tuple


tup1=(1,2,3,4,5)
tup2=(6,7,8,9,10)
tup3=tup1+tup2
Output:
print(tup3)
run1:
(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
deleting elements in tuple
#program to delete a tuple
tup1=(1,2,3,4,5)
del tup1
print(tup1)
------------
error message:
NameError: name 'tup1' is not defined
Basic tuple operations
 length-len
 concatenation: +
 repetition: *
 maximum:max
 minimum:min
 comparison(>,<,==)
 iteration:for
 membership:in
write a program to swap two values using tuple
assignment
val1=10
val2=20
print("before swapping")
print("val1=",val1)
print("val2=",val2)
(val1,val2)=(val2,val1)
print("after swaping")
print("val1=",val1)
print("val2=",val2)
Data Structure
 Contains values : Values are stored and performs functionality
 Where in values which are stored and perform specific functionality, i.e,
Data stored in a structured manner
 Wherein, in python we have int, float, string, list, tuple, set, dict and so on.
 Using these data, we must be :
 how to code & where to use it
 Data are always based on time and memory complexity
 Where should data persist, after creating it
 That’s why, Data as always stored in RAM(Primary Memory) instead Secondary
memory
 Reason why we use RAM is that can be accessed faster comparatively than any
other storage.
 short-term memory
 RAM faster than data on a hard disk
 can be read and changed in any order
 Determining your system's performance
 Shutdown: RAM clears out and there is no data stored in it
Dictionaries
 Creating elements of dictionary
 Accessing elements of dictionary
 Basic operators of dictionary
 Built in methods of dictionary
dict
 Key : value
 dict is an ordered collection.
 It stores the elements using keys
 Keys are also objects
 Keys and Values can be heterogenous.
 Keys must be unique
 If we try to store information with duplicate key,
existing data will be replaced.
 If key is unique, data can be duplicated.
Dictionaries
 Is a set of key: value pairs, with the requirement that
the keys are unique
 Mapping between a set of indices (keys) and a set of
values. Each key maps to a value.
 Dictionaries are mutable, that is, they are modifiable.
 A pair of braces creates an empty dictionary: { }. Ex: d
= { } || empty_d = dict() //Empty
state diagram
creating a dictionary
 dict():new dictionary with no elements.
 example:
#creating empty dictionary
d=dict()
print (d)
--------------
output:
{}
creating dictionaries with elements
d={10:"A",20:"B",30:"C“} print(d)

d={10:2.3,4.5:"abc", "xyz":20} print(d)

d={10:"A",20:"A",30:"A"} print(d)

# creating dictionaries element


thisdict ={
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
-------------
output
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
Ordered or Unordered?
 When we say that dictionaries are ordered, it means
that the items have a defined order, and that order will
not change.

 Unordered means that the items does not have a


defined order, you cannot refer to an item by using an
index.

 Changeable: Dictionaries are changeable, meaning


that we can change, add or remove items after the
dictionary has been created.
duplicates not allowed
 Dictionaries cannot have two items with the same key:
#duplicates not allowed
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964,
"year": 2020
}
print(thisdict)
output
{'brand': 'Ford', 'model': 'Mustang', 'year': 2020}
Dictionary Items - Data Types
 The values in dictionary items can be of any data type

#example for String, int, boolean, and list data types


thisdict = {
"brand": "Ford",
"electric": False,
"year": 1964,
"colors": ["red", "white", "blue"]
}
print("dictionary is:",thisdict)
output
dictionary is: {'brand': 'Ford', 'electric': False, 'year': 1964,
'colors': ['red', 'white', 'blue']}
type()
#Print the data type of a dictionary
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(type(thisdict))
-------------
<class 'dict'>
 Initialize list of integers

 dict={'RollNo': [101,102,103], Name':['John','Smith','Sam']}


 d={'a':10,'Name':'John',9:10}

 Update()
 d.update({"abc":302})
Traversing:
for k in d.keys():
print(k)

for v in d.values():
print(v)

for k,v in d.items():


print(k,v)
built in methods
conti..
List, Tuple, Set, dict :
 List is a non-homogeneous/heterogenous data
structure that stores the elements in single row and
multiple rows and columns
 Tuple is also a non-homogeneous data structure that
stores single row and multiple rows and columns
 Set data structure is also non-homogeneous data
structure but stores in single row
 Dictionary is also a non-homogeneous data structure
which stores key value pairs
Duplicate elements
 List allows duplicate elements
 Tuple allows duplicate elements

 Set will not allow duplicate elements


 Dictionary doesn’t allow duplicate keys.
Symbol, Creation and Empty object
 List can be represented by [ ]
 Tuple can be represented by ( )
 Set can be represented by { }
 Dictionary can be represented by { }

 Creation:  Representing Empty object:


 l= list()  l=[]
 t= tuple()  t=()
 a=set()
 a=set()
 d=dict()
 d={}
 Nested among all : List, Tuple, Set, Dict

 Duplicate elements : List, Tuple, Dict


 No Duplicate elements : set

 Mutable: list, set, dict


 Immutable : tuple

 All modifier Methods : list, set, dict


 Methods (index, count) : tuple
 Methods without indexing & slicing : set

 Allows both mutable & Immutable : List, Tuple, dict


 Allows only Immutable object : set

 Ordered elements: list, tuple, dict


 Unordered elements : set

You might also like