Python Unit 3
Python Unit 3
UNIT-3
STRINGS AND LISTS
3.1. STRINGS:
P Y T H O N – S T R I N G
0 1 2 3 4 5 6 7 8 9 10 11 12
PRASANNANJANEYULU Y
UNIT-3 STRINGS AND LISTS
1. If we try to retrieve characters at out of range index then ‘IndexError’ exception will
be raised.
Ex:
sample_str = "Python Supports Machine Learning."
print (sample_str[1024]) #index must be in range
# IndexError: string index out of range
2. String index must be of integer data type. You should not use a float or any other data
type for this purpose. Otherwise, the Python subsystem will flag a TypeError exception
as it detects a data type violation for the string index.
Ex:
sample_str = "Welcome post"
print (sample_str[1.25]) #index must be an integer
# TypeError: string indices must be integers
PRASANNANJANEYULU Y
UNIT-3 STRINGS AND LISTS
#t
#h
#o
#n
PRASANNANJANEYULU Y
UNIT-3 STRINGS AND LISTS
PRASANNANJANEYULU Y
UNIT-3 STRINGS AND LISTS
PRASANNANJANEYULU Y
UNIT-3 STRINGS AND LISTS
find(str [,i Searches for ‘str’ in complete String (if i and j var=”Tech Beamers”
[,j]]) not defined) or in a sub-string of String (if i str=”Beam”
and j are defined).This function returns the print (var.find(str))
index if ‘str’ is found else returns ‘-1’. #5
where, var=”Tech Beamers”
i=search starts from this index str=”Beam”
j=search ends at this index. print (var.find(str,4))
#5
var=”Tech Beamers”
str=”Beam”
print (var.find(str,7))
# -1
PRASANNANJANEYULU Y
UNIT-3 STRINGS AND LISTS
Ex:
S = 'Hello', S[0] == 'H', S[1] == 'e', S[2] == 'l', S[3] == 'l', S[4] == 'o'
If you specify a negative index, then it is counted from the end, starting with the number -
1. That is, S[-1] == 'o', S[-2] == 'l', S[-3] == 'l', S[-4] == 'e', S[-5] == 'H'.
Sub String Slice: Slice with two parameters S[a:b] returns the substring of length b - a,
starting with the character at index a and lasting until the character at index b, not
including the last one.
Ex: S=”Hello”
S[1:4] == 'ell', and you can get the same substring using S[-4:-1]
Slices with two parameters never cause IndexError
If you omit the first index, the slice will start from the beginning. If you omit the last
index, the slice will go to the end of the string.
Ex:
s = "Hello"
print(s[1:]) # prints "ello"
print(s[:6]) # prints “Hello”
print(s[-4:]) # prints “ello”
Any slice of a string creates a new string and never modifies the original one.
Subsequence Slice: If you specify a slice with three parameters S[a:b:d], the third
parameter specifies the step, same as for function range(). In this case only the characters
with the following index are taken: a a + d, a + 2 * d and so on, until and not including the
character with index b. If the third parameter equals to 2, the slice takes every second
character, and if the step of the slice equals to -1, the characters go in reverse order. For
example, you can reverse a string like this: S[::-1].
Ex:
s = "Hello"
print(s[0:5:2]) # prints “Hlo”
3.2. LISTS:
Python lists are ordered sequences of items. For instance, a sequence of n numbers
might be called S:
S = s0, s1, s2, s3, …, sn-1
A list or array is a sequence of items where the entire sequence is referred to by
a single name (i.e. s) and individual items can be selected by indexing (i.e. s[i]).
Python lists are dynamic. They can grow and shrink on demand.
Python lists are also heterogeneous, a single list can hold arbitrary data types.
Python lists are mutable sequences of arbitrary objects.
PRASANNANJANEYULU Y
UNIT-3 STRINGS AND LISTS
my_list = []
# list of integers
my_list = [1, 2, 3]
PRASANNANJANEYULU Y
UNIT-3 STRINGS AND LISTS
PRASANNANJANEYULU Y
UNIT-3 STRINGS AND LISTS
Extend operator can be used to concatenate one list into another. It is not possible to
store the value into the third list. One of the existing list has to store the
concatenated result.
Example:
list_c = list_a.extend(list_b)
print list_c # Output: NoneType
print list_a # Output: [1, 2, 3, 4, 5, 6, 7, 8]
print list_b # Output: [5, 6, 7, 8]
Slicing:
Given a string s, the syntax for a slice is:
s[ startIndex : pastIndex ]
The startIndex is the start index of the string. pastIndex is one past the end of
the slice.
Ex:
theList = [1, 2, 3, 4, 5, 6, 7, 8]
theList[2:5] #[3,4,5]
Since Python list follows the zero-based index rule, so the first index starts at
0.
In slicing, if you leave the start, then it means to begin slicing from the 0th
index.
Ex:
theList[:2]
[1, 2]
While slicing a list, if the stop value is missing, then it indicates to perform
slicing to the end of the list. It saves us from passing the length of the list
as the ending index.
Ex:
theList[2:]
[3, 4, 5, 6, 7, 8]
Reverse A Python List Using The Slice Operator
o It is effortless to achieve this by using a special slice syntax (::-1). But
please remember that reversing a list this way consumes more
memory than an in-place reversal.
o Here, it creates a shallow copy of the Python list which requires
long enough space for holding the whole list.
Ex:
theList[::-1]
[8, 7, 6, 5, 4, 3, 2, 1]
PRASANNANJANEYULU Y
UNIT-3 STRINGS AND LISTS
Iteration:
Python provides a traditional for-in loop for iterating the list. The for
statement makes it super easy to process the elements of a list one by one.
for element in theList:
print(element)
If you wish to use both the index and the element, then call the enumerate()
function.
for index, element in enumerate(theList):
print(index, element)
If you only want the index, then call the range() and len() methods.
for index in range(len(theList)):
print(index)
Ex:
theList = ['Python', 'C', 'C++', 'Java', 'CSharp']
Output –
I like Python
I like C
I like C++
I like Java
I like CSharp
List methods:
list.append(elem) -- adds a single element to the end of the list. Common error: does
not return the new list, just modifies the original.
list.insert(index, elem) -- inserts the element at the given index, shifting elements to the
right.
list.extend(list2) -- adds the elements in list2 to the end of the list. Using + or += on a list
is similar to using extend().
list.index(elem) -- searches for the given element from the start of the list and returns
its index. Throws a ValueError if the element does not appear (use "in" to check without
a ValueError).
list.remove(elem) -- searches for the first instance of the given element and
removes it (throws ValueError if not present)
list.sort() -- sorts the list in place (does not return it). (The sorted() function shown
later is preferred.)
list.reverse() -- reverses the list in place (does not return it)
list.pop(index) -- removes and returns the element at the given index. Returns the
rightmost element if index is omitted (roughly the opposite of append()).
Example:
list = ['larry', 'curly', 'moe']
list.append('shemp') ## append elem at end
list.insert(0, 'xx') ## insert elem at index 0
list.extend(['yy', 'zz']) ## add list of elems at end
print(list) #['xx','larry','curly','moe','shemp','yy','zz']
print(list.index('curly')) ## 2
PRASANNANJANEYULU Y
UNIT-3 STRINGS AND LISTS
PRASANNANJANEYULU Y
UNIT-3 STRINGS AND LISTS
functions of List
Function Description
Return True if all elements of the list are true (or if the list is empty). lst1=[1,2,3,4]
lst2=[10,11,0,14]
print(all(lst2)) # False
Return True if any element of the list is true. If the list is empty, return False. lst=[1,2,0,4]
list() t=(1,2,3,4)
print(list(t)) # [1,2,3,4]
Return a new sorted list (does not sort the list itself).
sorted() my_list=[6,3,8,4,1]
print(sorted(my_list)) # [1,3,4,6,8]
PRASANNANJANEYULU Y
UNIT-3 STRINGS AND LISTS
2.5
2.3
PRASANNANJANEYULU Y