Unit 4 Python
Unit 4 Python
Unit IV
Strings and Lists: String as a compound data type, Length, Traversal and the for loop, String slices, String
comparison, Looping and counting, List values, Accessing elements, List length, List membership, Lists and for
loops, List operations, List deletion. Cloning lists, Nested lists .
Strings are arrays of bytes representing Unicode characters. However, Python does not have a character data
type, a single character is simply a string with a length of 1. Square brackets can be used to access elements
of the string.
Creating a String
Strings in Python can be created using single quotes or double quotes or even triple quotes.
Strings in python are surrounded by either single quotation marks, or double quotation marks.'hello' is the same
as "hello".You can display a string literal with the print() function:
String Length
a = "Hello, World!" 13
print(len(a))
slice() Constructor
The slice() constructor creates a slice object representing the set of indices specified by range(start, stop,
step).
Syntax:
slice(stop)
slice(start, stop, step)
Parameters:
start: Starting index where the slicing of object starts.
stop: Ending index where the slicing of object stops.
step: It is an optional argument that determines the increment between each index for slicing.
Extending indexing
In Python, indexing syntax can be used as a substitute for the slice object. This is an easy and convenient way
to slice a string both syntax wise and execution wise.
Syntax
string[start:end:step]
start, end and step have the same mechanism as slice() constructor.
String ='ASTRING' AST
SR
print(String[:3])
print(String[1:5:2])
WEBSOL PYTHON BCA 2 UNIT 4 WEBSOL
String Comparison in Python
Method 1: Using Relational Operators
The relational operators compare the Unicode values of the characters of the strings from the zeroth index till
the end of the string. It then returns a boolean value according to the operator used.
Example: “Geek” == “Geek” will return True as the Unicode of all the characters are equal
word = 'raspberry' 3
count = 0
for letter in word:
if letter == 'r':
count = count + 1
print(count)
# Python program to illustrate Hello Geek
# while loop Hello Geek
count = 0 Hello Geek
while (count < 3):
count = count + 1
print("Hello Geek")
word = 'banana' 3
count = 0
for letter in word:
if letter == 'a':
count = count + 1
print(count)
fruit = "fruit" f
index = 0 r
while index < len(fruit): u
letter = fruit[index] i
WEBSOL PYTHON BCA 2 UNIT 4 WEBSOL
print(letter) t
index = index + 1
string = "Apple" A
i=0 Ap
App
one = string[0:i+1] Appl
two = string[0:i+2] Apple
three = string[0:i+3]
four = string[0:i+4]
five = string[0:i+5]
print(one)
print(two)
print(three)
print(four)
print(five)
List
A list in Python is used to store the sequence of various types of data. Python lists are mutable type its mean we
can modify its element after it created. However, Python consists of six data-types that are capable to store the
sequences, but the most common and reliable type is the list.
A list can be defined as a collection of values or items of different types. The items in the list are separated with
the comma (,) and enclosed with the square brackets [].Lists are used to store multiple items in a single variable.
Characteristics of Lists
List Length
To determine how many items a list has, use the len() function:
Access Items
List items are indexed and you can access them by referring to the index number:
Negative Indexing
-1 refers to the last item, -2 refers to the second last item etc.
To remove a list element, you can use either the del statement if you know exactly which element(s) you are deleting or
the remove() method
Cloning Lists
If we want to modify a list and also keep a copy of the original, we need to be able to make a copy of the list
itself, not just the reference. This process is sometimes called cloning, to avoid the ambiguity of the word copy.
Nested list
A nested list is a list within a list. Python provides features to handle nested list gracefully and apply common functions to
manipulate the nested lists.
Creating a Matrix
Creating a matrix involves creating series of rows and columns. We can use for loop for creating the matrix
rows and columns by putting one python list with for loop inside another python list with for loop.We can use
the list comprehension with filtering feature by using the for loop within the sub-lists. Below we have a 2
dimensional list with one layer of sub-list inside a bigger list. We access selective elements from each of these
nested lists. By using a filter condition.
not in Returns True if a sequence with the specified value is not present in the object x not in y
1. 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.
x = [1,2,3,4,5] False
print(8 in x)
x = [1,2,3,4,5] True
print(3 in x)
not in’ operator- Evaluates to true if it does not finds a variable in the specified sequence and false otherwise.
x = [1,2,3,4,5] False
print(4 not in x)
x = [1,2,3,4,5] True
print(8 not in x)
List operations
append() Method : The append() method appends an element to the end of the list.
name = ["Amit", "Jai", "Sonu"] ['Amit', 'Jai', 'Sonu', 'Mohit']
name.append("Mohit")
print(name)
clear() Method : The clear() method removes all the elements from a list.
name = ["Amit", "Jai", "Sonu"] []
name.clear()
print(name)
WEBSOL PYTHON BCA 2 UNIT 4 WEBSOL
Copy() :
The copy() method returns a copy of the specified list.
print(x)
print(name)
count()
The count() method returns the number of elements with the specified value.
x = name.count("amit")
print(x)
extend()
The extend() method adds the specified list elements (or any iterable) to the end of the current list.
list2 = ["naman","raj"]
list1.extend(list2)
print(list1)
sort()
the sort() method sorts the list ascending by default.You can also make a function to decide the sorting
criteria(s).
name.sort()
print(name)