0% found this document useful (0 votes)
5 views23 pages

List & String in Python

The document outlines a course on Programming for Problem-Solving at the School of Computer Science and Engineering, focusing on Python data types such as lists, strings, tuples, sets, and dictionaries. It details prerequisites, course objectives, and various operations on lists and strings, including creation, access, modification, and built-in functions. The course aims to equip students with the skills to write and structure Python programs effectively.

Uploaded by

yashyadav3602
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views23 pages

List & String in Python

The document outlines a course on Programming for Problem-Solving at the School of Computer Science and Engineering, focusing on Python data types such as lists, strings, tuples, sets, and dictionaries. It details prerequisites, course objectives, and various operations on lists and strings, including creation, access, modification, and built-in functions. The course aims to equip students with the skills to write and structure Python programs effectively.

Uploaded by

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

Name of the School: School of Computer Science and Engineering

Course Code: E2UC102C Course Name: PROGRAMMING FOR PROBLEM-SOLVING

Data Types in Python


 List
 String
 Tuple
 Set
 Dictionary

Faculty Name: Dr. Subhash Chandra Gupta Programe Name: B.Tech (CSE)
Prerequisite/Recapitulations

 Basic Programming and Logic knowledge


 Mathematics in 10th class

Faculty Name: Dr. Subhash Chandra Gupta Programe Name: B.Tech (CSE)
Objectives

Upon completion of the course, students will be able to

 Read, write, execute by hand simple Python programs.


 Structure simple Python programs for solving problems.
 Decompose a Python program into functions.
 Represent compound data using Python lists, tuples, dictionaries.

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

Let us consider an example:


L1 = [56, 78.94, "India"]
In the above example, L1 is a list, which contains 3 elements.
The first element is 56 (integer), the second is 78.94 (float), third is "India" (string).
Select all the correct statements given below.
 All elements in a list should be of same data type.
 Lists are immutable.
 Lists are ordered and can contain other lists as elements.
 Indexing can be used with lists to access individual items only if there are no nested lists.

Faculty Name: Dr. Subhash Chandra Gupta Programe Name: B.Tech (CSE)
Create and Access a List

A list is created by using square brackets [ ] to enclose elements separated by commas ,.


For example:
a = [1, 2, 3, 4, 5, 6, 7, 8]
print(a) # Output: [1, 2, 3, 4, 5, 6, 7, 8]
We can also use the list() constructor to create a list:
colors = list(("red", "blue", "green", "yellow"))
type(colors) # <class 'list'>
print(colors) # Output: ['red', 'blue', 'green', 'yellow']
To access elements in a list, we use the indexing operator [ ] with the index of the element.
• Indices range from 0 to N-1, where N is the number of elements in the list, when moving from left to right.
We can also access elements in reverse, from right to left.
• The starting index is -1, which points to the last element and it goes up to -N, where N is the total number
of elements.
• Trying to access an element beyond the index range will result in an error.
Examples: Nested List:
print(a[0]) # Output: 1 mat=[[1,2,3],[4,5,6],[7,8,9]]
print(a[-1]) # Output: 8 print(mat[2][0])
print(a[8]) # Returns: "IndexError" because valid indices are 0 to 7
print(a[-8]) # Output: 1
Faculty Name: Dr. Subhash Chandra Gupta Programe Name: B.Tech (CSE)
Add elements to a List

Lists are mutable (changeable). Meaning we 2. Using extend()


can add and remove elements from a list. We use the extend() method to add all the items of an iterable (list,
Python provides different methods to add items tuple, string, dictionary, etc.) to the end of the list.
to a list. For example,
numbers = [1, 3, 5]
1. Using append() even_numbers = [4, 6, 8]
The append() method adds one item at the end numbers.extend(even_numbers)
of the list. print("List after append:", numbers)
For example,
numbers = [21, 34, 54, 12] Output
print("Before Append:", numbers) List after append: [1, 3, 5, 4, 6, 8]
numbers.append(32) Here, numbers.extend(even_numbers) adds all the elements
print("After Append:", numbers) of even_numbers to the numbers list.

Output 3. Using insert()


Before Append: [21, 34, 54, 12] We use the insert() method to add an element at the specified index.
After Append: [21, 34, 54, 12, 32] numbers = [10, 30, 40] # insert an element at index 1 (second
position)
Here, append() adds 32 at the end of the array. numbers.insert(1, 20)
print(numbers) # [10, 20, 30, 40]
Faculty Name: Dr. Subhash Chandra Gupta Programe Name: B.Tech (CSE)
Write the code to create 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.

Constraints: Test Case 1:


1 <= n <= 10 L1=[] Expected Output:
Sample Test case: l=int(input())
3 for i in range(l):
Apple L1.append(input()) 3
123 print(L1) Apple
banana
['apple','123','banana'] 123
banana
Explanation:
['Apple’,’123','banana']
The first line of input contains the integer n.
Next n Lines, the input is taken.
Every input value is added to the list.
Print the result as an output
Faculty Name: Dr. Subhash Chandra Gupta Programe Name: B.Tech (CSE)
Deleting or removing elements

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

List slicing is an operation that extracts a subset Slices Example Description


of elements from a list and creates a new list with a = [9, 8, 7, 6, 5, 4]
a[0:3] a[0:3] Print a part of list from index 0 to 2
them. [9, 8, 7]

Syntax for List slicing: a[:4] Default start value is 0.


a[:4]
[9, 8, 7, 6] Prints the values from index 0 to 3

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

Here is a list of built-in functions that can be applied on a list:


1. len(): It calculates the length of the list i.e., the number of elements in the list.
print(len(['a', 'b', 'c', 'd', 'e']))
5
2. max(): Returns the item with the highest value from the list
print(max([1, 2, 3, 4, 5]))
5
3. min(): Returns the item with the lowest value from the list.
print(min([1, 2, 3, 4, 5]))
1
4. sorted(): Returns a sorted version of the given list, leaving the original list unchanged.
origlist = [1, 5, 3, 4, 7, 9, 1, 27]
print(sorted(origlist)
[1, 1, 3, 4, 5, 7, 9, 27]
5. sum(): Returns the sum of all the elements of a list. It works only on an integer list.
print(sum([1, 5, 3, 4, 7, 9, 1, 27]))
57

Faculty Name: Dr. Subhash Chandra Gupta Programe Name: B.Tech (CSE)
Built function and methods

sort(key = None, reverse = False) copy()


Sort the items of the list in place in ascending order Return the shallow copy of the list
If the parameter reverse = True, then the list is sorted Equivalent to a[:]
in place in descending order.
x = ['z', 'f', 'e', 'a','b', 'g', 't']
x = ['z', 'f', 'e', 'a','b', 'g', 't'] y = x.copy()
x.sort() print(y)
print(x) ['z', 'f', 'e', 'a', 'b', 'g', 't']
['a', 'b', 'e', 'f', 'g', 't', 'z'] print(x is y)
x.sort(key = None, reverse = True) False
print(x)
['z', 't', 'g', 'f', 'e', 'b', 'a']

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

In Python, there are 5 fundamental operations which can be performed on strings:


1. Indexing
2. Slicing
3. Concatenation
4. Repetition
5. Membership
Let us learn about Indexing first.

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.

Python has two types of indexing:


 Positive Indexing: It begins from the first character of a string, starting with 0. This method helps in accessing
the string from the beginning.
 Negative Indexing: It begins from the last character of a string, starting with -1. This method helps in accessing
the string from the end.

Faculty Name: Dr. Subhash Chandra Gupta Programe Name: B.Tech (CSE)
Indexing on String

Let us consider the below example:

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

Sample Input and Output:


This is my first String
f
S

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

String slices: For example:


A segment of a string is called a slice. Selecting a slice is str = 'Hello World!'
similar to selecting a character. print str # Prints complete string
print str[0] # Prints first character of the string
Subsets of strings can be taken using the slice operator ([ ] print str[2:5] # Prints characters starting from
and [:]) with indexes starting at 0 in the beginning of the 3rd to 5th
string and working their way from -1 at the end. print str[2:] # Prints string starting from 3rd
character print
Slice out substrings, sub lists, sub Tuples using index. str * 2 # Prints string two times
Syntax:[Start: stop: steps] print str + "TEST" # Prints concatenated string

 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

There are many methods to operate on String. 9. replace(old, new [, max])


1. isalnum() Returns true if string has at least 1 character and all Replaces all occurrences of old in string with new
characters are alphanumeric and false otherwise. or at most max occurrences if max given.
Syntax: String.isalnum() Example:
2. isalpha() Returns true if string has at least 1 character and all >>> string="Nikhil Is Learning"
characters are alphabetic and false otherwise. >>> string.replace('Nikhil','Neha')
3. isdigit() Returns true if string contains only digits and false 'Neha Is Learning'
otherwise. 10. split() Splits string according to delimiter str (space if
4. islower() Returns true if string has at least 1 cased character not provided) and returns list of substrings;
and all cased characters are in lowercase and false otherwise. Syntax: String.split()
5. isnumeric() Returns true if a string contains only numeric Example:
characters and false otherwise. >>> string="Nikhil Is Learning"
6. isspace() Returns true if string contains only whitespace >>> string.split()
characters and false otherwise. ['Nikhil', 'Is', 'Learning']
7. istitle() Returns true if string is properly “titlecased” and 11. count() Occurrence of a string in another string
false otherwise. Example:
8. isupper() Returns true if string has at least one cased >>> string='Nikhil Is Learning'
character and all cased characters are in uppercase >>> string.count('i')
and false otherwise. 3

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

Compare Two Strings Join Two or More Strings


We use the == operator to compare two strings. If In Python, we can join (concatenate) two or more strings using
two strings are equal, the operator returns True. the + operator.
Otherwise, it returns False. greet = "Hello,
For example, name = "Jack"
str1 = "Hello, world!" result = greet + name # using + operator
str2 = "I love Python." print(result) # Output: Hello, Jack
str3 = "Hello, world!" In the above example, we have used the + operator to join two
# compare str1 and str2 strings: greet and name.
print(str1 == str2)
# compare str1 and str3 Iterate Through a Python String
print(str1 == str3) We can iterate through a string using a for loop.
Output: For example,
False greet = 'Hello' Output:
True # iterating through greet string H
for letter in greet: e
In the above example, print(letter) l
str1 and str2 are not equal. Hence, the result is False. l
str1 and str3 are equal. Hence, the result is True. o

Faculty Name: Dr. Subhash Chandra Gupta Programe Name: B.Tech (CSE)
String functions and methods

Python String Length Python String Formatting (f-Strings)


In Python, we use the len() method to find the length
of a string. Python f-Strings make it really easy to print values
and variables.
For example, For example,
greet = 'Hello' name = 'Cathy'
# count length of greet string country = 'UK'
print(len(greet)) print(f'{name} is from {country}')
# Output: 5
Output
String Membership Test Cathy is from UK
We can test if a substring exists within a string or not,
using the keyword in. Here, f'{name} is from {country}' is an f-string.

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)

You might also like