Professional Documents
Culture Documents
A list can be created by putting the value inside the square bracket,
and values are separated by commas.
Lists can contain any sort of object: numbers, strings, and even other
lists.
Lists Creation
Example 1:
Output:
print(num_list[-1])
print(num_list[0])
print(num_list[-6])
print(num_list)
num_list[4] = 33
print(num_list)
In Python, we can store lists within another list (nested lists). The
following code that makes one list containing other lists and values
with different data types.
print(data)
Accessing Elements from Lists
print(data[1])
print(data[0][0])
inner_list = data[1]
print(inner_list[0])
init_list = [0]*3
print(init_list)
Output:
[0, 0, 0]
two_dim_list = [ [0]*3 ] *3
print(two_dim_list)
Output:
print(two_dim_list)
Output:
Slicing Lists
Omitting the ending index means that the slice contains the list
elements from the starting index to the end of the list.
print(num_list[3:])
Slicing with an Ending Index
Omitting the starting index means that the slice contains the list
elements from the beginning of the list up to the ending index.
print(num_list[:4])
Omitting the starting and ending index means it will print all the
elements of the list.
print(num_list[:])
We can reverse a list by specifying the step as -1. The following code
returns the num_list items in reverse order without giving the start
and end index.
print(num_list[ : :-1])
List Comprehension
Python List comprehensions are used for creating new lists from
other iterables like tuples, strings, arrays, lists, etc.
Syntax
Example 1:
print(List1)
Output: [0, 1, 2, 3, 4]
Example 2:
Create a list that contains square of all odd numbers from range 1 to
10.
Program:
print (square_odd)
square_odd = []
if x%2!=0:
square_odd.append(x**2)
print (square_odd)
Example 3:
Output: ['ml', 'mi', 'md', 'ul', 'ui', 'ud', 'gl', 'gi', 'gd']
Example 4:
list_fruit = ["Apple","Mango","Banana","Avocado"]
print(first_letters)
print (power_of_2)
Example 6:
#range 1 to 10
print(list1)
print("\nExtracted digits")
print (numbers)
Example 9:
print("\nMultiplication Table")
for i in table:
print (i)
Add Elements in a List
There are two methods for adding new items into a list,
insert() and append() methods. The new item can be a
string, a number, or even another list. We can use both
methods to expand a list.
.insert()
fruits.insert(1, "pineapple")
print(fruits)
.append()
fruits = ["apple","orange","cherry"]
fruits.append("pineapple")
print(fruits)
Output: ['apple', 'orange', 'cherry', pineapple']
Note:
students += ["zyx"]
print(students)
+ Operator
print(students)
even_numbers = [4, 6, 8]
numbers.extend(even_numbers)
Reversing a List
my_list = [1, 2, 3, 4, 5]
reversed_list = list(reversed(my_list))
print(reversed_list)
Output: [5, 4, 3, 2, 1]
Removing Items from a List
list1 = [1, 2, 3, 4, 5, 6,
7, 8, 9, 10, 11, 12]
print("Initial List: ")
print(list1)
# Removing elements from List
list1.remove(5)
list1.remove(6)
print("\nList after Removal of two elements: ")
print(List)
Output:
Initial List:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
List after Removal of two elements:
[1, 2, 3, 4, 7, 8, 9, 10, 11, 12]
Example 2:
# Creating a List
List = [1, 2, 3, 4, 5, 6,
7, 8, 9, 10, 11, 12]
# Removing elements from List
# using iterator method
for i in range(1, 5):
List.remove(i)
print("\nList after Removing a range of elements: ")
print(List)
Output:
List after Removing a range of elements:
[5, 6, 7, 8, 9, 10, 11, 12]
Method 2: Using pop()
Syntax: list_name.pop(index)
index (optional) – The value at index is popped out and removed.
If the index is not given, then the last element is popped out and
removed.
Return: Returns The last value or the given index value from the list.
l = [1, 2, 3, 4]
Output:
Popped element: 4
List after pop(): [1, 2, 3]
Example 2: With index
list1 = [1, 2, 3, 4, 5, 6]
print(list1.pop(3), list1)
Output: 4 [1, 2, 3, 5, 6]
poped_item = list1.pop(-2)
Output:
New list [1, 2, 3, 4, 6]
Poped Item 5
When the specified value is found inside the list, the statement
returns True; otherwise, it returns False.
Example 1:
num_list = []
if not num_list:
Example 2:
if 'swift' in languages:
else:
Example 3:
List Methods
Methods Description
Append() Add an element to the end of the list
Extend() Add all elements of a list to another list
Insert() Insert an item at the defined index
Remove() Removes an item from the list
Clear() Removes all items from the list
Syntax: list_name.count(object)
print(list1.count(('Cat', 'Bat')))
print(list1.count([1, 2]))
list1 = [1, 1, 1, 2, 3, 2, 1]
print(list1.count(1, 2)) #Error
Sort() Sort items in a list in ascending order
#Ascending Order
unsorted_list = [2,4,5,32,6,255,5,42]
unsorted_list.sort()
print("Now it is sorted:", unsorted_list)
#Decending Order
numbers = [1, 3, 4, 2]
numbers.sort(reverse=True)
print(numbers)
reverse() Reverse the order of items in the list
list1 = [2, 1, 3, 5, 3, 8]
list1.reverse()
print(list1) # [8, 3, 5, 3, 1, 2]
copy() Returns a copy of the list
Function Description
sum() Sums up the numbers in the list
numbers = [1,2,3,4,5,1,4,5]
Sum = sum(numbers)
print(Sum)
Sum = sum(numbers, 20)
print(Sum)
max() return maximum element of a given list
Example 1:
var1 = 4
var2 = 8
var3 = 2
max_val = max(var1, var2, var3)
print(max_val) # 8
Example 2:
var1 = "Hello"
var2 = "Hi"
var3 = "Hru"
max_val = max(var1, var2, var3, key=len)
print(max_val)
Example 3:
list = [1.2, 1.3, 0.1]
max_value = max(list)
print(max_value)
min() return minimum element of a given list
var1 = 4
var2 = 8
var3 = 2
max_val = min(var1, var2, var3)
print(max_val) # 8
string1 = "PPSclass"
# printing length of string1
print(len(string1)) # 8
map() returns a list of the results after applying the
given function to each item of a given
iterable
Example 1:
def addition(n):
return n + n
numbers = (1, 2, 3, 4)
result = map(addition, numbers)
print(list(result))
Example 2:
# List of strings
l = ['sat', 'bat', 'cat', 'mat']
# map() can listify the list of strings
individually
test = list(map(list, l))
print(test)
Output: [['s', 'a', 't'], ['b', 'a', 't'], ['c', 'a', 't'],
['m', 'a', 't']]
filter() tests if each element of a list is true or not
# sequence
sequence = ['g', 'e', 'e', 'j', 'k', 's', 'p', 'r']
Output:
() — an empty tuple
(1.0, 9.9, 10) — a tuple containing three numeric objects
("apple", "banana", "mango") — a tuple containing four string
objects
('10', 101, True) — a tuple containing a string, an integer, and a
Boolean object
my_tuple = tuple("pps")
print (my_tuple) # output: ('p', 'p', 's')
Example 2:
a=1;b=2;c=3
my_tuple = (a, b, c)
print (my_tuple) #output: (1, 2, 3)
Also, other objects like lists and tuples can comprise a tuple,
like this:
a_tuple = (0, [1, 2, 3], (4, 5, 6), 7.0)
print(a_tuple) # output: (0, [1, 2, 3], (4, 5, 6), 7.0)
print(type(a_tuple)) # type: <class 'tuple'>
last_language = my_tuple[-1]
print(last_language) # Output: 'JavaScript'
Example 2:
a_tuple = (0, [1, 2, 3], (4, 5, 6), 7.0)
print('The first element:', a_tuple[0])
print('The second last element:', a_tuple[-2])
Find the second element of the inner tuple, at index 2.
print(a_tuple[2][1]) # Output: 5
Slicing to Access a Range of Elements
Use slicing to access a range of elements in a tuple.
# Slice tuple
my_tuple = ('Python', 'Java', 'C++', 'JavaScript')
first_two_languages = my_tuple[:2]
print(first_two_languages)
num_tuple = 2, 4, 5, 7, 8, 10
print(num_tuple[:3])
print(num_tuple[4:])
print(num_tuple[-3:])
print(num_tuple[2:5])
Output:
(2, 4, 5)
(8, 10)
(7, 8, 10)
(5, 7, 8)
Access the Elements of a Nested Tuples
To access the elements of a nested tuple, you can use multiple
indices to access elements at different levels of nesting. It is the
same as accessing the element of the nested list.
# Creates a nested tuple with elements
my_tuple = ('Python', ('Java', 'C++'), ('JavaScript', ('Scala', 'Kotlin')))
Multiplying a tuple
Multiplying a tuple by an integer produces a tuple containing the
original tuple repeated that many times.
my_tuple = (1, 7, 9, 8)
print(my_tuple * 2) # Output: (1, 7, 9, 8, 1, 7, 9, 8)
del tuple1
print(tuple1)
Example 1
Lists more preferable iterable objects than tuples are that a list
object provides more methods.
But lists occupy more space than tuples, i.e., list object occupies
more memory than a tuple object.
import sys
a_list = ['abc', 'xyz', 123, 231, 13.31, 0.1312]
a_tuple = ('abc', 'xyz', 123, 231, 13.31, 0.1312)
print('The list size:', sys.getsizeof(a_list), 'bytes')
print('The tuple size:', sys.getsizeof(a_tuple), 'bytes')
Tuple Element Swapping
x = 19
y = 91
print('Before swapping:')
print(f'x = {x}, y = {y}')
(x, y) = (y, x)
print('After swapping:')
print(f'x = {x}, y = {y}')
Tuple Functions
print(tup.count(22)) #Output: 3
min(tup) # Output: 1
t = (4, 5, 1)
print(all(t)) # Output: True
t = (5, 0, 3, 1, False)
print(all(t)) # Output: False
t = ()
print(all(t)) Output: True
t = (4, 5, 1)
print(any(t)) # Output: True
t = (0, 0, False)
print(any(t)) # Output: False
t = ()
print(any(t)) # Output: False
Tuples VS Lists:
Similarities Differences
Both ‘tuples’ and ‘lists’ Tuples that contain immutable elements can be
can be nested. used as a key for a dictionary.
Set
A set is a built-in Python data structure used to store a collection of
unique items, potentially of mixed data types, in a single variable.
Unordered – the items of a set don’t have any defined order. This
means that they do not preserve the original order in which they
were created.
Example:
>>> x = {'a','b','c'}
>>> print(x)
>>> x
Example:
>>> x = {'a','b','c'}
>>> print(x[0])
Example:
>>> x = {'a','b','c','c'}
>>> print(x)
Note:
Python set itself is mutable (we can remove items from it or add
new ones), but its items must be immutable data types, like integers,
floats, tuples, or strings.
set4 = {1, 1, 'pps', 'pps', 8.6, (1, 2, 3), None} # mixed datatypes
set5 = {1, 1, ' pps', 'pps', 8.6, [1, 2, 3], {1, 2, 3}}
print('Set5:', set5)
s = set('Alpha')
empty1 = {}
empty2 = set()
myset.add("d")
print(myset) # Output: {'d', 'c', 'b', 'a'}
Set Membership
True
False
True
False
False
print(item)
Note: The order of the output values can differ from the succession
shown in the original set.
# Initial set
myset = set()
myset.add('a')
myset.update('fgh') # a string
print(myset) # Output: {'e', 'f', 'b', 'h', 'd', 'c', 'a', 'g'}
# Initial set
myset = {1, 2, 3, 4}
myset = {2, 3}
myset.clear()
print(myset) # empty set Output: set()
myset.pop()
len() – returns the set size (the number of items in the set).
min() and max() – return the smallest/largest item in the set and
are mostly used for the sets with numeric values.
sum() – returns the sum of all items of the set containing only
numeric values.
print('\n')
# A set with string items
print('\n')
all() – returns True if all items of the set evaluate to True, or if the
set is empty.
myset = {4, 2, 5, 1, 3}
print(sorted(myset)) # [1, 2, 3, 4, 5]
a = {1, 2, 3, 4, 5}
b = {4, 5, 6, 7}
Set Union
The union of two (or more) Python sets returns a new set of all the
unique items from both (all) sets. It can be performed using the |
operator or the union() method:
print(a | b) # {1, 2, 3, 4, 5, 6, 7}
print(b | a) # {1, 2, 3, 4, 5, 6, 7}
print(a.union(b)) # {1, 2, 3, 4, 5, 6, 7}
print(b.union(a)) # {1, 2, 3, 4, 5, 6, 7}
As we can see, for the union operation, the order of sets doesn’t
matter: we can write a | b or b | a with the identical result, and the
same can be said about using the union() method.
The syntax for the union operation on more than two Python
sets is the following: a | b | c or a.union(b, c).
Set Intersection
The intersection of two (or more) Python sets returns a new set of
the items common to both (all) sets. It can be performed using the
& operator or the intersection() method:
a = {1, 2, 3, 4, 5}
b = {4, 5, 6, 7}
print(a.intersection(b)) # {4, 5}
print(b.intersection(a)) # {4, 5}
Again, in this case, the order of sets doesn’t matter: a & b or b & a
will yield the same result, and the same is true when using the
intersection() method.
Set Difference
The difference of two (or more) Python sets returns a new set
containing all the items from the first (left) set that are absent in
the second (right) set.
In the case of more than two sets, the operation is performed from
left to right. For this set operation, we can use the - operator or
the difference() method:
a = {1, 2, 3, 4, 5}
b = {4, 5, 6, 7}
print(a - b) # {1, 2, 3}
print(b - a) # {6, 7}
print(a.difference(b)) # {1, 2, 3}
print(b.difference(a)) # {6, 7}
The syntax for the difference operation on more than two Python
sets is the following: a - b - c or a.difference(b, c). In such cases, we
first compute a - b, then find the difference between the resulting
set and the next one to the right, which is c, and so on.
b = {4, 5, 6, 7}
print(a ^ b) # {1, 2, 3, 6, 7}
print(b ^ a) # {1, 2, 3, 6, 7}
print(a.symmetric_difference(b)) # {1, 2, 3, 6, 7}
print(b.symmetric_difference(a)) # {1, 2, 3, 6, 7}
a = {1, 2, 3, 4, 5}
b = {4, 5, 6, 7}
c = {7, 8, 9}
a.symmetric_difference(b, c)
There are several other useful methods and operators for working
with two or more Python sets:
Example:
# Compare 3 sets, and return a set with items that is present in all 3
sets:
A = {1, 2, 3, 4}
B = {2, 3, 4, 5, 6}
C = {4, 5, 6, 9, 10}
A.intersection_update(B, C)
A &= B
A &= C
# sets of numbers
A = {1, 3, 5, 7, 9}
B = {2, 3, 5, 7, 11}
A.difference_update(B)
A -= B
A. symmetric_difference_update(B)
A ^= B
print('A. symmetric_difference_update(B): ', A)
Output:
A = {1, 2, 3}
B = {4, 5, 6}
print(A.isdisjoint(B)) # True
A = {1, 2, 3}
B = {1, 2, 3, 4, 5}
A <= B
print (A <= B) # True
print(A.issubset(B)) # True
print(B.issubset(A)) # False
# Return True if all elements of a set B are in set A. Then Set A is the
superset of set B.
A = {4, 1, 3, 5}
B = {6, 0, 4, 1, 5, 0, 3, 5}
print(B>=A) # True
Set Comprehension
Syntax
Set comprehension has a simple and elegant syntax that consists of
two parts:
The for loop and the if statement are the two fundamental building
blocks of set comprehension.
The for loop iterates over the iterable object, and the if statement
filters the elements based on a condition.
Example 1:
numbers = [1, 2, 3, 4, 5]
print(squared_numbers)
Example 2:
Filtering elements in a list
numbers = [1, 2, 3, 4, 4, 5, 6, 6, 6, 7, 7]
print(even_numbers)
Output: {2, 4, 6}
Example 3:
input_list = [1, 2, 3, 4, 4, 5, 6, 6, 6, 7, 7]
output_set = set()
if var % 2 == 0:
output_set.add(var)
Create a new set called vowel_words that contains only the words
from the words list that contain at least one vowel.
Example
print(vowel_words)
Example 4:
print(myList)
print(newSet)
Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Example 6:
Create a set from elements of another set
mySet = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
newSet = {element ** 2 for element in mySet}
print("The Newly Created set is:")
print(newSet)
Output:
The Newly Created set is:
{64, 1, 4, 36, 100, 9, 16, 49, 81, 25}
Filter or Delete elements from a set
mySet = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
print("The existing set is:")
print(mySet)
mySet = {element for element in mySet if element % 2 == 0}
print("The modified set is:")
print(mySet)
Output:
The existing set is:
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
The modified set is:
{2, 4, 6, 8, 10}
Question: Create a set that hold elements that are less than and
greater than 6.
Key Takeaways
Set comprehension may be a concise and effective way to form
a new set based on an existing iterable object, such as a list or a
tuple.
The syntax for set comprehension comprises two parts: a new
set and an expression that defines the value of each element
within the set.
It can incorporate a variable that takes each value within the
iterable object and a conditional statement that filters the
elements.
Best practices include keeping it basic, utilizing significant
variable names, and utilizing curly braces to extend
meaningfulness.
Set comprehension may be a capable and exquisite highlight of
Python that can assist you in writing more brief and readable
code and spare you time and exertion.
Quiz
1. What is set comprehension in Python?
A way to create a new set based on an existing iterable object
A way to convert a list into a set
A way to modify an existing set
A way to create a new list
2. Which of the following is the syntax for set comprehension?
new_set = {expression for variable in iterable if condition}
new_set = {expression in variable for iterable if condition}
new_set = {expression for variable if iterable and condition}
new_set = {expression for variable in iterable while condition}
3. What does the 'if' statement do in set comprehension?
It filters the elements based on a condition
It defines the value of each element in the new set
It defines the variable that takes each value in the iterable
object
It iterates over the iterable object
Hash Table:
Keys are immutable (which cannot be changed) data types that can
be either strings or numbers.
The hashing is used to maintain the integrity of the hash table and
also ensure the uniqueness of the hash code.
It gives the hash value of the key passed to the has function. The
resulting hash value is used as an index (hash code) in a hash table.
These values are then used to lookup for a value associated with its
unique key.
Properties:
Example 1:
# initializing objects
int_val = 4
str_val = 'pps'
flt_val = 24.56
Output:
The integer hash value is : 4
The string hash value is : -5570917502994512005
The float hash value is : 1291272085159665688
Example 2:
# initializing objects
# tuple is immutable
tuple_val = (1, 2, 3, 4, 5)
# list is mutable
list_val = [1, 2, 3, 4, 5]
# Printing the hash values.
# Notice exception when trying to convert mutable object
Output:
Creating a Dictionary
Example 2:
dict1 = { "key1": "value1"}
print(dict1[key1]) # Access key1
Output: value1
Integers, floats, strings, and tuples are hashable data types (and
they are also immutable) while lists are an unhashable data type
(and they are mutable).
Python uses hash values to quickly access a dictionary's values.
9. update()
The update() method is useful whenever we want
to merge dictionaries or add new key:value pairs
using an iterable (iterables are, for instance, lists or
tuples).
10. len()
Print the number of items in the dictionary:
d = {1: "one", 2: "three"}
print(len(d))
Output
2
11. Values ()
The values() method returns a view object that
displays a list of all the values in the dictionary.
Example 1:
marks = {'Physics':67, 'Maths':87}
print(marks.values())
Output
dict_values([67, 87])
values = sales.values()
del[sales['apple']]
people[3] = {}
people[3]['name'] = 'Luna'
people[3]['age'] = '24'
people[3]['gender'] = 'Female'
people[3]['married'] = 'No'
print(people[3])
Output:
{'name': 'Luna', 'age': '24', 'gender': 'Female', 'married':
'No'}
Explanation: In the above program, we create an
empty dictionary 3 inside the dictionary people.
Then, we add the key:value pair i.e people[3]['Name']
= 'Luna' inside the dictionary 3. Similarly, we do this
for key age, gender and married one by one.
Output:
brand
model
year
Example 2
Print all values in the dictionary, one by one:
for x in dict1:
print(dict1[x])
Output:
Ford
Mustang
1964
Example 3
You can also use the values() function to return values
of a dictionary:
for x in dict1.values():
print(x)
Output:
Ford
Mustang
1964
Iterating Through a Nested Dictionary
Example 1: How to iterate through a Nested
dictionary?
people = {1: {'Name': 'John', 'Age': '27', 'Gender':
'Male'},
2: {'Name': 'Marie', 'Age': '22', 'Gender':
'Female'}}
for p_id, p_info in people.items():
print("\nPerson ID:", p_id)
for key in p_info:
print(key + ':', p_info[key])
Output
Person ID: 1
Name: John
Age: 27
Gender: Male
Person ID: 2
Name: Marie
Age: 22
Gender: Female
Python Check if Key Exists in Dictionary
To determine if a specified key is present in a
dictionary use the in keyword:
Example 1:
Check if "model" is present in the dictionary:
dict1 = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
if "model" in dict1:
print("Yes, 'model' is one of the keys in the thisdict
dictionary")
Output
Yes, 'model' is one of the keys in the dict1 dictionary
Dictionary Comprehension
Dictionaries are data types in Python which allows us
to store data in key/value pair.
Dictionary Comprehension can be helpful in creating
new dictionaries from existing dictionaries and
iterables.
Syntax for dictionary comprehension:
{key: value for (key, value) in iterable}
import random
customers=
["Alex","Bob","Carol","Dave","Flow","Katie","Nate"]
discount_dict = {customer:random.randint(1,100) for
customer in customers}
print(discount_dict)
Output:
{'Alex': 12, 'Bob': 83, 'Carol': 15, 'Dave': 70, 'Flow': 70,
'Katie': 51, 'Nate': 96}
Create a Python Dictionary from Two Iterables
What if we already have pre-defined iterables that
contain the keys and values? Say, we have two lists,
list_1 and list_2 – with list_1 containing the keys and
list_2 containing the corresponding values.
Note 1: We can now use Python's zip() function to zip
these two lists to generate the key-value pairs.
Note 2: The zip function takes in a sequence of
iterables as the argument, and returns an iterator of
tuples, as shown in the image below.
Example
double_quote = "aa"
# Another double-quote string
triple_quote = '''aaa'''
# Multiline String
message = """
Welcome to Galgotias University
Welcome to MCA Course
"""
# An empty string with single quote
second_empty_string = ""
The inserted values are read as a string, but we can convert them into
other data types.
Similarly, it returns dict, int, float, tuple, bool class when the object
is a dictionary, integer, float, tuple, or Boolean, respectively.
ASCII encodes 128 characters mainly in the English language that are
used in processing information in computers and programming.
import string
ascii_upper_case = string.ascii_uppercase
# Output: ABCDEFGHIJKLMNOPQRSTUVWXYZ
print(ord(one_letter))
Output:
65
66
67
68
69
Output:
%
,
?
R
d
>
String Properties
1. Zero Index: The first element in a string has an index of zero, while
the last element has an index of len(string) - 1.
Example:
immutable_string = "Accountability"
print(len(immutable_string))
print(immutable_string.index('A'))
print(immutable_string.index('y'))
Output:
14
0
13
2. Immutability: This means that we cannot update the characters in
a string.
Example:
immutable_string = "Accountability"
Example:
immutable_string = "Accountability"
print(id(immutable_string))
immutable_string = "Bccountability"
print(id(immutable_string)
test_immutable = immutable_string
print(id(test_immutable))
Output:
2815347848432
2815347848496
2815347848496
Conclusion:
3. Concatenation
joining two or more strings together to get a new string with the +
symbol.
Example:
first_string = "PPS"
second_string = " Subject"
third_string = "Python programming path"
Output
PPS Subject
PPS Subject Python programming path
4. Repetition
print("PPS" * 3)
Output
PPSPPSPPS
We can access any element in a string with its index value. We can
also take subsets of a string by slicing between two index values.
# Index 0
print(main_string[0]) # OUTPUT: I
# Index 1
print(main_string[1]) # OUTPUT: White Space
# Slicing 1
print(main_string[0:11]) # OUTPUT: I will lear
# Slicing 2:
print(main_string[-18:]) # OUTPUT: C in PPS Subject.
# Slicing and concatenation
print(main_string[0:11] + ". " + main_string[-18:])
Example
greet = 'Hello'
Output
0H
1e
2l
3l
4o
Updating a character
Another method is using the string slicing method. Slice the string
before the character you want to update, then add the new character
and finally add the other part of the string again by string slicing.
Example:
Initial String:
Hello, I'm a boy
# Rule 1
list1 = list(String1)
list1[2] = 'p'
String2 = ' '.join(list1)
print("\nUpdating character at 2nd Index: ")
print(String2)
Output
# Rule 2
String3 = String1[0:2] + 'p' + String1[3:]
print (String1[0:2])
print (String1[3:])
print(String3)
Output
He
lo, I'm a boy
Heplo, I'm a boy
We can only assign a completely new value to the variable with the
same name.
Example
Output
Initial String:
Hello, I'm a boy
# Updating a String
String1 = "Welcome to PPS Class"
print("\nUpdated String: ")
print(String1)
Output
Updated String:
Welcome to PPS Class
Deleting a character
When we try to delete the character using the del keyword, it will
generate an error.
Example
Output
Initial String:
Hello, I'm a Geek
Slicing
But using slicing we can remove the character from the original
string and store the result in a new string.
Example
Output
Initial String:
Hello, I'm a boy
# Deleting a character
# of the String
String2 = String1[0:2] + String1[3:]
print (String1[0:2])
print (String1[3:])
He
lo, I'm a boy
Example
Output
Initial String:
Hello, I'm a boy
# Deleting a String
# with the use of del
del String1
print("\nDeleting entire String: ")
print(String1)
Output
When two strings are compared using relational operators (>, <, ==,
etc.), the elements of the two strings are compared by their ASCII
decimal numbers index by index.
Output
False
False
Note: When the strings are of the same length, it compares the ASCII
decimal numbers of each element from index 0 until it finds
elements with different ASCII decimal numbers. For example:
Output: True
In the above code snippet, the first two elements have the same
ASCII decimal numbers; however, there is a mismatch in the third
element, and since d is greater than c, it returns True.
In a situation where all the ASCII numbers for the elements match,
the longer string is greater than the shorter one. For example:
String Methods
1. str.split(sep=None, maxsplit=-1):
The string split method contains two attributes: sep and maxsplit.
When this method is called with its default values, it splits the string
anywhere there is a whitespace. This method returns a list of
strings:
Output
We can see that the string isn't split nicely because the split string
contains ,. We can use sep=','to split wherever there is a ,:
print(string.split(sep=','))
Output
print(string.split(sep=', '))
Output
2. str.strip([chars])
string = " Apple Apple Apple no apple in the box apple apple "
stripped_string = string.strip()
print(stripped_string)
Output: Apple Apple Apple no apple in the box apple apple
capitalized_string = left_stripped_string.capitalize()
print(capitalized_string)
right_stripped_string = (
capitalized_string
.rstrip('apple')
.rstrip()
.rstrip('apple')
.rstrip()
)
print(right_stripped_string)
Output: No apple in the box
In the above code snippet, we have used the lstrip and rstrip
methods that remove trailing whitespaces or characters from the
left and right sides of the string respectively. We have also used the
capitalize method, which converts a string to a sentence case.
3. str.zfill(width)
Output: 000.8
4. str.isalpha()
This method returns True if all the characters in the string are
alphabets; otherwise, it returns False:
# Alphabet string
alphabet_one = "Learning"
print(alphabet_one.isalpha())
# Contains whitspace
alphabet_two = "Learning Python"
print(alphabet_two.isalpha())
# isupper()
string_three = string_one.upper() # converts string to uppercase
print(string_three.isupper()) # True
# istitle()
print(string_one.istitle()) # True
String with Suffix and Prefix
sentences = ['Time to master data science', 'I love statistical
computing', 'Eat, sleep, code']
# endswith()
for one_sentence in sentences:
print(one_sentence.endswith(('science', 'computing', 'Code')))
Output
True
True
False
# startswith()
for one_sentence in sentences:
print(one_sentence.startswith(('Time', 'I ', 'Ea')))
Output
True
True
True
str.find(substring)
It returns the lowest index if the substring is present in the string;
otherwise, it returns -1.
str.rfind(substring) returns the highest index.
The str.index(substring) and str.rindex(substring) also return
the lowest and highest index of the substring respectively if found.
If the substring isn't present in the string, they raise ValueError.
string = "programming"
# find() and rfind() examples
print(string.find('m'))
print(string.find('pro'))
print(string.rfind('m'))
print(string.rfind('game'))
Output
6
0
7
-1