[go: up one dir, main page]

0% found this document useful (0 votes)
248 views8 pages

Unit 4 Python

Strings can be created using single, double, or triple quotes in Python. The len() function returns the length of a string. Strings can be indexed and sliced similar to lists. Lists store multiple items of different types and are mutable. The len() function also returns the length of a list. List items can be accessed by index and looped through using a for loop. Methods like append(), insert(), remove(), pop(), and clear() can be used to modify lists. Nested lists can be created to represent a matrix structure with multiple lists within a list.

Uploaded by

Vikas Pareek
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
0% found this document useful (0 votes)
248 views8 pages

Unit 4 Python

Strings can be created using single, double, or triple quotes in Python. The len() function returns the length of a string. Strings can be indexed and sliced similar to lists. Lists store multiple items of different types and are mutable. The len() function also returns the length of a list. List items can be accessed by index and looped through using a for loop. Methods like append(), insert(), remove(), pop(), and clear() can be used to modify lists. Nested lists can be created to represent a matrix structure with multiple lists within a list.

Uploaded by

Vikas Pareek
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/ 8

WEBSOL PYTHON BCA 2 UNIT 4 WEBSOL

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

To get the length of a string, use the len() function.

a = "Hello, World!" 13
print(len(a))

Strings indexing and splitting


Like other languages, the indexing of the Python strings starts from 0. For example, The string "HELLO" is
indexed as given in the below figure.
WEBSOL PYTHON BCA 2 UNIT 4 WEBSOL
String Slicing
To access a range of characters in the String, method of slicing is used. Slicing in a String is done by using a
Slicing operator (colon).
Python slicing is about obtaining a sub-string from the given string by slicing it respectively from start to
end.

Python slicing can be done in two ways.


 slice() Constructor
 Extending Indexing

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.

String ='ASTRING' String slicing


s1 = slice(3)
AST
s2 = slice(1, 5, 2)
print(String[s1]) SR
print(String[s2])
GITA

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

print("Geek" == "Geek") True


print("Geek" < "geek") True
print("Geek" > "geek") False
print("Geek" != "Geek") False

Looping and Counting


We will implement a few of the methods that we described earlier to show how they can be done. This program
demonstrates another pattern of computation called a counter. The variable count is initialized to 0 and then
incremented each time an “r” is found. When the loop exits, count contains the result: the total number of r‟s.

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)

Traversal and the for loop


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.

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)

for name in ["raj", "Amit", "Kiran", Hi raj. welcome to Bikaner!


"Aman"]: Hi Amit. welcome to Bikaner!
show = "Hi " + name + ". welcome to Hi Kiran. welcome to Bikaner!
Bikaner!" Hi Aman. welcome to Bikaner!
print(show)

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

The list has the following characteristics:

 The lists are ordered.


 The element of the list can access by index.
 The lists are the mutable type.
 The lists are mutable types.
 A list can store the number of various elements.

thislist = ["apple", "banana", "cherry"] ['apple', 'banana', 'cherry']


print(thislist)
WEBSOL PYTHON BCA 2 UNIT 4 WEBSOL
List Items
List items are ordered, changeable, and allow duplicate values.List items are indexed, the first item has index
[0], the second item has index [1] etc.

List Length
To determine how many items a list has, use the len() function:

thislist = ["apple", "banana", "cherry"] 3


print(len(thislist))

Access Items
List items are indexed and you can access them by referring to the index number:

thislist = ["apple", "banana", "cherry"] banana


print(thislist[1])

Negative Indexing

Negative indexing means start from the end

-1 refers to the last item, -2 refers to the second last item etc.

thislist = ["apple", "banana", "cherry"] cherry


print(thislist[-1])

Loop Through a List


You can loop through the list items by using a for loop: List is equivalent to arrays in other languages, with the
extra benefit of being dynamic in size. In Python, the list is a type of container in Data Structures, which is used
to store multiple data at the same time. Unlike Sets, lists in Python are ordered and have a definite count.
There are multiple ways to iterate over a list in Python.

thislist = ["apple", "banana", "cherry"] apple


for x in thislist: banana
print(x) cherry
# Python3 code to iterate over a list 1
list = [1, 3, 5, 7, 9] 3
5
7
# Using for loop 9
for i in list:
print(i)
WEBSOL PYTHON BCA 2 UNIT 4 WEBSOL
Removing elements from the list
Python provides the remove() function which is used to remove the element from the list.

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

list1 = ['physics', 'chemistry', 1997, 2000]; ['physics', 'chemistry', 2000]


del list1[2];
print list1
# Creating a List [1, 3, 4, 5]
List = [1, 2, 3, 4, 5]
List.remove(2)
print(List)

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.

list1 = [10, 22, 44, 23, 4] [10, 22, 44, 23, 4]


list2 = list(list1) [10, 22, 44, 23, 4]
print(list1)
print(list2)

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.

years = [['January', 'February', 'March'], ['April', 'May', 'June'], ['July', 'August',


'September'],['October','November','December']]
# Nested List comprehension with an if condition
years = [years for sublist in years for years in sublist if len(years) <= 4]
print(years)
['May', 'June', 'July']
WEBSOL PYTHON BCA 2 UNIT 4 WEBSOL
Membership Operators
Membership operators are operators used to validate the membership of a value. It test for membership in a
sequence, such as strings, lists, or tuples.Membership operators are used to test if a sequence is presented in an
object:

Operator Description Example


Returns True if a sequence with the
in x in y
specified value is present in the object
Returns True if a sequence with the
not in
specified value is not present in the object x not in y

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.

name = ["amit", "karan", "charu"] ['amit', 'karan', 'charu']


['amit', 'karan', 'charu']
x = name.copy()

print(x)
print(name)

count()
The count() method returns the number of elements with the specified value.

name = ["amit", "karan", "charu","amit"] 2

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.

list1 = ["amit", "karan"] ['amit', 'karan', 'naman', 'raj']

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 = ['raj', 'amit', 'jiya'] ['amit', 'jiya', 'raj']

name.sort()

print(name)

You might also like