List & String in Python
List & String in Python
Faculty Name: Dr. Subhash Chandra Gupta Programe Name: B.Tech (CSE)
Prerequisite/Recapitulations
Faculty Name: Dr. Subhash Chandra Gupta Programe Name: B.Tech (CSE)
Objectives
Faculty Name: Dr. Subhash Chandra Gupta Programe Name: B.Tech (CSE)
Introduction
List in Python is a fundamental data structure that serves as a container for holding an ordered collection of
items/objects.
• The items of a list need not be of same data type.
• We can retrieve the elements of a list using "index".
• List can be arbitrary mixture of types like numbers, strings and other lists as well.
• They are of variable size i.e they can grow or shrink as required
• They are mutable which means the elements in the list can be changed/modified
Faculty Name: Dr. Subhash Chandra Gupta Programe Name: B.Tech (CSE)
Create and Access a List
Your task is to :
• Take an integer n as input from the user.
• Ask the user to enter n items one by one to store them in the list data structure.
• At the end just print the list.
One or more elements of a list can be deleted using The list remove(element) method is also used for this purpose.
the keyword del. This can as well delete the entire This method searches for the given element in the list and removes
list. the first matching element.
dlist = ['red', 'orange', 'blue', 'green', 'yellow', 'red'] remlist = ['red', 'orange', 'blue', 'green', 'yellow', 'red']
print(dlist) remlist.remove('green')
['red', 'orange', 'blue', 'green', 'yellow', 'red'] print(remlist)
del dlist[5] ['red', 'orange', 'blue', 'yellow', 'red']
print(dlist)
The pop(index) method removes and returns the item at index, if
['red', 'orange', 'blue', 'green', 'yellow']
index is provided.
del dlist[2:]
If index is not provided as an argument, then pop() method removes
print(dlist)
and returns the last element.
['red', 'orange']
plist = ['red', 'orange', 'blue', 'green', 'yellow', 'cyan']
del dlist
elem = plist.pop()
The clear() method is used to clear the contents of a print(elem)
list and make it empty. 'cyan'
plist.clear() elem = plist.pop(-1)
print(plist) print(elem)
[] 'yellow'
print(plist) ['red', 'orange', 'blue', 'green‘]
Faculty Name: Dr. Subhash Chandra Gupta Programe Name: B.Tech (CSE)
List Slicing
Listname[start:stop] a[1:]
a[1:]
Prints values from index 1 onwards
[8, 7, 6, 5, 4]
Listname[start:stop:steps] a[:]
a[:] Prints the entire list
[9, 8, 7, 6, 5, 4]
default start value is 0 a[2:2]
a[2:2]
Prints an empty slice
[]
a[0:6:2]
default stop value is n -1 a[0:6:2]
[9, 7, 5]
Slicing list values with step size 2
a[::-1]
a[::-1] Prints the list in reverse order
[:] this will print the entire list [4, 5, 6, 7, 8, 9]
a[-3:]
a[-3:] Prints the last 3 items in list
[6, 5, 4]
[2:2] this will create an empty slice a[:-3]
a[:-3] Prints all except the last 3 items in list
[9, 8, 7]
Faculty Name: Dr. Subhash Chandra Gupta Programe Name: B.Tech (CSE)
Understand mutability in List and Indexing
Lists are mutable which means the items in it can be changed. Mutability involves altering specific data without
complete recreation. List items can be changed by assigning new values using the indexing operator ( [ ]).
Example Description
a = [1, 2, 3, 4, 5]
a[0] = 100 Changing a single element
print(a) # Output: [100, 2, 3, 4, 5]
a = [1, 2, 3, 4, 5]
a[0:3] = [100, 100, 100] Changing multiple elements
print(a) # Output: [100, 100, 100, 4, 5]
a = [1, 2, 3, 4, 5]
Certain elements from a list can also be
a[0:3] = [ ]
removed by assigning an empty list to them
print(a) # Output: [4, 5]
a = [1, 2, 3, 4, 5]
The elements can be inserted into a list by
a[0:0] = [20, 30, 45]
squeezing them into an empty slice at the desired location
print(a) # Output: [20, 30, 45, 1, 2, 3, 4, 5]
Faculty Name: Dr. Subhash Chandra Gupta Programe Name: B.Tech (CSE)
Built function and methods
Faculty Name: Dr. Subhash Chandra Gupta Programe Name: B.Tech (CSE)
Built function and methods
reverse()
Reverse the order of elements of the list in place
x = ['z', 'f', 'e', 'a','b', 'g', 't']
x.reverse()
print(x)
['t', 'g', 'b', 'a', 'e', 'f', 'z']
Faculty Name: Dr. Subhash Chandra Gupta Programe Name: B.Tech (CSE)
String in Python
Strings in python are represented with prefixing and suffixing the characters with quotation marks (either single quotes (')
or double quotes (")).
Characters in a string are accessed using an index which is an integer (either positive or negative).
It starts from 0 to n-1, where n is the number of characters in a string.
Strings are immutable which means contents cannot be changed once they are created.
The function input() in python is a string by default.
In computer programming, a string is a sequence of characters. Example: Python String
For example, "hello" is a string containing a sequence of characters 'h', 'e', 'l', 'l', and 'o'.
We use single quotes or double quotes to represent a string in Python. For example, # create string type variables
name = "Python"
# create a string using double quotes print(name)
string1 = "Python programming" message = "I love Python."
# create a string using single quotes print(message)
string1 = 'Python programming‘
Output
Here, we have created a string variable named string1. Python
The variable is initialized with the string I love Python.
Python Programming.
Faculty Name: Dr. Subhash Chandra Gupta Programe Name: B.Tech (CSE)
Operation on String
To access a specific character from a string, we use its position called Index which is enclosed within square brackets [].
Index value always starts with 0.
Faculty Name: Dr. Subhash Chandra Gupta Programe Name: B.Tech (CSE)
Indexing on String
a = "HELLO"
print(a[0]) # prints the 0th index value, where Output will be 'H‘
At index '0', the character 'H' is present, so Indexing starts from the left and increments to the right.
print(a[-1]) # prints -1 index value, where Output will be 'O‘
At index '-1', the character 'O' is present, so Indexing starts from the right and increments to the left.
Given a string "This is my first String". Write the code to achieve the following.
print the entire string
print the character f using positive/forward indexing
print the character S using negative/backward indexing
Faculty Name: Dr. Subhash Chandra Gupta Programe Name: B.Tech (CSE)
String Properties
Python Strings are immutable Python Multiline String
In Python, strings are immutable. That means the characters of a We can also create a multiline string in Python. For
string cannot be changed. this, we use triple double quotes """ or triple single
For example, quotes '''.
message = 'Hola Amigos'
message[0] = 'H' For example,
print(message) # multiline string
Output message = """
TypeError: 'str' object does not support item assignment Never gonna give you up
Never gonna let you down
However, we can assign the variable name to a new string. """
For example, print(message)
message = 'Hola Amigos' # assign new string to message variable Output
message = 'Hello Friends' Never gonna give you up
prints(message); # prints "Hello Friends“ Never gonna let you downIn
>>> greeting = 'Hello, world!' the above example, anything inside the enclosing
>>> new_greeting = 'J' + greeting[1:] triple-quotes is one multiline string.
>>> new_greeting
'Jello, world!'
Faculty Name: Dr. Subhash Chandra Gupta Programe Name: B.Tech (CSE)
String Slicing
Slicing will start from index and will go up to stop in step Output:
of steps. Hello World!
Default value of start is 0, H
Stop is last index of list llo
And for step default is 1 llo World!
Hello World!Hello World!
Hello World!TEST
Faculty Name: Dr. Subhash Chandra Gupta Programe Name: B.Tech (CSE)
Python Escape Sequence Characters
There are some characters that have a special meaning when used in a string. Code Description
But what do you do if you would like to insert that character in the string as it
is, without invoking its special meaning? \' Single Quote
\” Double Quote
For understanding this, let us take a simple example. We use single quotes or
double quotes to define a string. Suppose, we define a string with single \ Backslash
quotes. The first occurrence of a single quote marks the start of the string and
the second occurrence marks the end of the string. Now, consider that we \n New Line
would like to have a single quote in our string. What do we do now? If we
\r Carriage Return
place a single quote just like that in the middle of the string, Python would
think that this is the end of the string, which is actually not. \t Tab
To insert these kinds of illegal characters, we need the help of a special \b Backspace
character like backslash \.
\f Form Feed
What is the escape character used in the below code? \ooo Octal Value
x = 'hello\'world' \xhh Hex Value
print(x)
Faculty Name: Dr. Subhash Chandra Gupta Programe Name: B.Tech (CSE)
String functions and methods
Faculty Name: Dr. Subhash Chandra Gupta Programe Name: B.Tech (CSE)
String functions and methods
12. find() Finding the index of the first occurrence of a Syntax: String.startswith(„string‟)
string in another string Example:
Syntax: String.find(„string‟) >>> string="Nikhil Is Learning"
Example: >>> string.startswith('N')
>>> string="Nikhil Is Learning" True
>>> string.find('k') 15. endswith()
2 Determines if string or a substring of string (if starting
13. swapcase() Converts lowercase letters in a string to index beg and ending index end are given) ends with
uppercase and viceversa substring str; returns true if so and false otherwise.
Syntax: String.find(„string‟) Syntax: String.endswith(„string‟)
Example: Example:
>>> string="HELLO" >>> string="Nikhil Is Learning"
>>> string.swapcase() >>> string.startswith('g')
'hello' True
14. startswith(str, beg=0,end=len(string))
Determines if string or a substring of string (if starting Note:
index beg and ending index end are given) starts with All the string methods will be returning either true or
substring str; returns true if so and false otherwise. false as the result
Faculty Name: Dr. Subhash Chandra Gupta Programe Name: B.Tech (CSE)
String functions and methods
Faculty Name: Dr. Subhash Chandra Gupta Programe Name: B.Tech (CSE)
String functions and methods
print('a' in 'program') # True This new formatting syntax is powerful and easy to
print('at' not in 'battle') # False use. From now on, we will use f-Strings to print
strings and variables.
Faculty Name: Dr. Subhash Chandra Gupta Programe Name: B.Tech (CSE)
References
TEXT BOOKS
1.Allen B. Downey, ``Think Python: How to Think Like a Computer Scientist‘‘, 2nd edition,
Updated for Python 3, Shroff/O‘Reilly Publishers, 2016.
2.R. Nageswara Rao, “Core Python Programming”, dreamtech
3. Python Programming: A Modern Approach, Vamsi Kurama, Pearson
REFERENCE BOOKS:
1. Core Python Programming, W.Chun, Pearson.
2. Introduction to Python, Kenneth A. Lambert, Cengage
3. Learning Python, Mark Lutz, Orielly
ONLINE :
https://www.programiz.com/python-programming/list
https://www.geeksforgeeks.org/python-data-types/?ref=lbp
https://www.youtube.com/watch?v=HvA7I0l0nqI
https://galgotias.codetantra.com
Faculty Name: Dr. Subhash Chandra Gupta Programe Name: B.Tech (CSE)