Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
39 views

Python Unit-3 Question Bank

The document discusses the three intrinsic sequence types in Python - lists, tuples, and strings. It explains their characteristics like mutability, syntax and examples of common operations. It also discusses iterators and their role in Python programming.

Uploaded by

karakamadhu4
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
39 views

Python Unit-3 Question Bank

The document discusses the three intrinsic sequence types in Python - lists, tuples, and strings. It explains their characteristics like mutability, syntax and examples of common operations. It also discusses iterators and their role in Python programming.

Uploaded by

karakamadhu4
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 88

Unit-3:

1. Write in brief about Sequence in Python. Discuss various


operations with suitable examples.
Explain three intrinsic sequence types of Python
language with examples?

In Python, a sequence is an ordered collection of elements, where each element is identified by an


index. The three intrinsic sequence types in Python are lists, tuples, and strings. Each type has its
characteristics and usage.

Lists:

Lists are mutable sequences, meaning you can modify their elements after they are created. Lists are
enclosed in square brackets `[ ]` and elements are separated by commas. Lists allow for flexible
storage of heterogeneous data types.

Example:

my_list = [1, 2, 'a', 'b', True]

Operations on Lists:

1. **Indexing and Slicing:** Accessing elements or a subset of elements from a list using index or
slicing.

print(my_list[0]) # Output: 1

print(my_list[2:4]) # Output: ['a', 'b']

2. **Appending and Extending:** Adding elements to the end of a list using `append()` or adding
multiple elements using `extend()`.

```python

my_list.append(3)

print(my_list) # Output: [1, 2, 'a', 'b', True, 3]

my_list.extend([4, 5])

print(my_list) # Output: [1, 2, 'a', 'b', True, 3, 4, 5]

```
3. **Inserting and Deleting:** Inserting elements at a specific position using `insert()` and
removing elements using `remove()` or `pop()`.
```python
my_list.insert(2, 'c')
print(my_list) # Output: [1, 2, 'c', 'a', 'b', True, 3, 4, 5]

my_list.remove('a')
print(my_list) # Output: [1, 2, 'c', 'b', True, 3, 4, 5]

popped_element = my_list.pop(3)
print(popped_element) # Output: 'b'
```

Tuples:
Tuples are immutable sequences, meaning their elements cannot be changed after creation.
Tuples are enclosed in parentheses `()` and elements are separated by commas. Tuples are
typically used for fixed collections of related data.

Example:
```python
my_tuple = (1, 2, 'a', 'b', True)
```

Operations on Tuples:
Tuples support most of the operations that lists do, except for those that modify the tuple.

Example:
```python
print(my_tuple[0]) # Output: 1
print(my_tuple[2:4]) # Output: ('a', 'b')
```

Strings:
Strings are immutable sequences of characters. They are enclosed in either single quotes `' '`
or double quotes `" "`. Strings behave like lists of characters, but they cannot be modified
after creation.

Example:
```python
my_string = "hello"
```
Operations on Strings:
Strings support various operations similar to lists and tuples, such as indexing, slicing,
concatenation, repetition, and more.

Example:
```python
print(my_string[0]) # Output: 'h'
print(my_string[1:4]) # Output: 'ell'

new_string = my_string + " world"


print(new_string) # Output: 'hello world'

repeated_string = my_string * 3
print(repeated_string) # Output: 'hellohellohello'
```
These intrinsic sequence types provide flexibility and versatility in handling different types of
data in Python. Lists are used for mutable sequences, tuples for immutable sequences, and
strings for sequences of characters.

2. What are iterators In python.


In Python, an iterator is an object that allows you to traverse through all the elements of a collection,
such as a list or a tuple, or to generate elements on-the-fly, such as in a loop. Iterators provide a way
to access elements of a collection sequentially without needing to know the internal structure of the
collection.

The basic protocol for an iterator in Python involves two methods:

__iter__(): This method returns the iterator object itself. It's used to initialize the iteration.

__next__(): This method returns the next element in the iteration. If there are no more elements, it
raises a StopIteration exception.

In Python, many built-in objects are iterable, meaning they have an __iter__() method that returns
an iterator. Examples include lists, tuples, dictionaries, strings, and more.

Here's an example of how you can use an iterator to iterate over a list:

my_list = [1, 2, 3, 4, 5]

my_iter = iter(my_list)

# Using next() to get the next element

print(next(my_iter))

# Output: 1

print(next(my_iter))

# Output: 2

# Using a loop to iterate through the remaining elements for item in my_iter:

print(item)

In this example:

We first create a list my_list.

Then, we create an iterator my_iter using the iter() function, which calls the __iter__() method of the
list.

We use next() to retrieve the first two elements from the iterator.

Finally, we use a loop to iterate through the remaining elements of the iterator.

Iterators are fundamental to Python's looping constructs and play a crucial role in lazy evaluation,
allowing for efficient memory usage and handling of large datasets.
3. Discuss the relation between tuples and lists, tuples and
dictionaries in detail.

Introduction

Python, being a flexible language, offers multiple data structures to store and manage data.
Understanding the unique characteristics and use cases of each structure is pivotal for
effective programming. In this tutorial, we will delve deep into the fundamental difference
between dictionary, list, tuple and set in Python four of Python’s primary data structures.

Overview

Python is rich with in-built data structures, making data manipulation and storage
convenient. Among these, list, tuple, set, and dictionary stand out due to their ubiquity in
various applications. These structures differ based on factors like mutability, order
preservation, and element uniqueness. Let's unpack the intricacies of the difference
between dictionary, list, tuple and set in Python.

What is a List in Python?

A list is a widely used versatile data structure that allows you to store a collection of items.
Lists are ordered, mutable (modifiable), and can contain elements of different data types,
such as strings, integers, floats, and even other lists. Lists are defined by enclosing a comma-
separated sequence of elements within square brackets []. You can access, modify, and
perform various operations on the elements of a list.

Here is the syntax for lists:

my_list = [element1, element2, element3, ...]

In the above syntax,

• my_list: This is the name of the list variable that you choose.
• [element1, element2, element3, ...]: These are the elements you want to store in the
list, separated by commas and enclosed in square brackets.

Here is an example Python program that will demonstrate the creation and manipulation
of lists:

# Create a list of integers

numbers = [1, 2, 3, 4, 5]

# Access and print elements of the list

print("The first element is:", numbers[0])

print("The third element is:", numbers[2])

# Modify an element of the list

numbers[1] = 10

# Add an element to the end of the list

numbers.append(6)

# Remove an element from the list

numbers.remove(3)

# Find the length of the list

length = len(numbers)
# Check if an element is in the list

if 4 in numbers:

print("4 is in the list")

# Iterate through the list

print("List elements:")

for num in numbers:

print(num)

# Sort the list in ascending order

numbers.sort()

# Reverse the list

numbers.reverse()

# Create a list of mixed data types

mixed_list = [1, "apple", 3.14, True]

# Nested lists (lists within a list)

nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

# Access elements of a nested list

print("Element at row 2, column 3:", nested_list[1][2])


The above code begins by creating a list named numbers using the list data structure in
Python, with the syntax:

numbers = [1, 2, 3, 4, 5]

This list contains five integer elements. Subsequently, the code showcases various list
operations, including element access and modification using index positions (e.g.,
numbers[0] accesses the first element), appending elements to the list using the append()
method, removing elements by value with the remove() method, finding the length of the
list using the len() function, checking for the presence of an element using the in operator,
and iterating through the list using a for loop.

It also demonstrates list sorting and reversing using the sort() and reverse() methods.
Furthermore, the code defines a nested list called nested_list, which contains three inner
lists.

Finally, it shows how to access an element within the nested list with the syntax:

Nested_list[1][2]

This accesses the element at row 2, column 3, which is 6.

What is a Tuple in Python?

A tuple is an ordered and immutable (unchangeable) collection of elements. Tuples are


defined by enclosing a comma-separated sequence of elements within parentheses (). Like
lists, tuples can store elements of different data types. However, once a tuple is created,
you cannot modify its contents. Tuples are often used when you want to ensure the data
remains constant or unchangeable.

Here is the syntax for tuples:

my_tuple = (element1, element2, element3, ...)

In the above syntax,

• my_tuple: This is the name of the tuple variable.


• (element1, element2, element3, ...): These are the elements enclosed in parentheses
and separated by commas.

Here is an example Python program that will demonstrate the creation of tuples and some
common operations on tuples:

# Create a tuple of mixed data types

my_tuple = (1, "apple", 3.14, True)

# Access elements of the tuple using indexing

print("The first element is:", my_tuple[0])

print("The second element is:", my_tuple[1])

# Attempting to modify a tuple will result in an error

# Uncommenting the line below will cause an error

# my_tuple[0] = 10

# Find the length of the tuple

length = len(my_tuple)

# Check if an element is in the tuple

if 3.14 in my_tuple:

print("3.14 is in the tuple")

# Iterate through the tuple


print("Tuple elements:")

for item in my_tuple:

print(item)

# Concatenate tuples

tuple1 = (1, 2, 3)

tuple2 = ("a", "b", "c")

concatenated_tuple = tuple1 + tuple2

# Repeat a tuple

repeated_tuple = tuple1 * 3

# Nested tuples

nested_tuple = ((1, 2), (3, 4), (5, 6))

# Access elements of a nested tuple

print("Element at row 2, column 1:", nested_tuple[1][0])

The above program begins by creating a tuple named my_tuple and accesses the elements
of the tuple using index positions. The first element (1) is accessed with my_tuple[0], and
the second element ("apple") is accessed with my_tuple[1].

The code also calculates the length of the tuple, checks for the presence of an element, and
iterates through the tuple using a for loop. The len() function is used to find and store the
length of the my_tuple tuple.
What is a Set in Python?

A set is an unordered collection of unique elements. Sets are defined by enclosing a comma-
separated sequence of elements within curly braces {} or by using the set() constructor. Sets
are primarily used for tasks that involve storing and manipulating a collection of distinct
values.

Here is the syntax for creating sets:

my_set = {element1, element2, element3, ...}

# OR

my_set = set([element1, element2, element3, ...])

In the above syntax,

• my_set: This is the name of the set variable.

• {element1, element2, element3, ...}: These are the elements.

Here is an example of working with sets in Python:

# Create a set of unique integers

my_set = {1, 2, 3, 4, 5}

# Attempting to add a duplicate element will have no effect

my_set.add(2)

# Remove an element from the set

my_set.remove(3)

# Check if an element is in the set


if 4 in my_set:

print("4 is in the set")

# Find the length of the set

length = len(my_set)

# Iterate through the set

print("Set elements:")

for item in my_set:

print(item)

# Perform set operations (union, intersection, difference)

set1 = {1, 2, 3}

set2 = {3, 4, 5}

union_set = set1 | set2

intersection_set = set1 & set2

difference_set = set1 - set2

# Convert a list to a set to remove duplicates

my_list = [1, 2, 2, 3, 4, 4, 5]

unique_set = set(my_list)

What is a Dictionary in Python?


Dictionaries are unordered collections of key-value pairs. Each key in a dictionary is unique,
and it is associated with a corresponding value. A dictionary is defined by enclosing a
comma-separated sequence of key-value pairs within curly braces {}. They are used for
efficient data retrieval and storage of key-associated values.

Here is the syntax for creating dictionaries:

my_dict = {key1: value1, key2: value2, key3: value3, ...}

In the above syntax,

• my_dict: This is the name of the dictionary variable.

• {key1: value1, key2: value2, key3: value3, ...}: These are the key-value pairs enclosed
in curly braces and separated by commas.

Here is an example of using a dictionary in Python:

# Create a dictionary of key-value pairs

my_dict = {"name": "John", "age": 30, "city": "New York"}

# Access values using keys

name = my_dict["name"]

age = my_dict["age"]

# Attempting to access a non-existent key will raise a KeyError

# Uncommenting the line below will cause an error

# country = my_dict["country"]

# Check if a key is in the dictionary


if "city" in my_dict:

print("City is in the dictionary")

# Find the number of key-value pairs in the dictionary

num_items = len(my_dict)

# Iterate through keys and values

print("Dictionary elements:")

for key, value in my_dict.items():

print(key, ":", value)

# Modify a value associated with a key

my_dict["age"] = 31

# Add a new key-value pair to the dictionary

my_dict["country"] = "USA"

# Remove a key-value pair from the dictionary

del my_dict["city"]

Difference Between List, Tuple, Set, and Dictionary

Having grasped the fundamental attributes of Python's core data structures - list, tuple, set,
and dictionary - it becomes imperative to discern their distinctive aspects. These nuances
can greatly influence the choice of data structure for specific tasks.

1. Mutability
Mutability refers to the ability of an object to change its state or content after its creation.

• List: Lists are mutable. This means that after defining a list, you can alter its content
– be it changing, adding, or removing elements. The ability to modify lists makes
them versatile, especially when you need a collection that will undergo various
transformations during runtime.

• Tuple: In stark contrast, tuples are immutable. Once created, their content remains
static. This fixed nature makes tuples hashable and usable as dictionary keys. They're
especially suitable when you need to ensure data integrity and ensure certain values
remain constant throughout a program.

• Set: Sets are mutable, allowing insertion and removal of elements. However, since
they only house unique values, any attempt to add a duplicate value will be ignored.
This makes them invaluable for tasks like deduplication.

• Dictionary: These are mutable, granting you the flexibility to add, remove, or change
key-value pairs. However, their keys, much like tuple elements, need to be of
immutable types.

2. Ordering

Ordering relates to whether a data structure maintains a consistent sequence of its


contained elements.

• List: Lists are inherently ordered. The sequence in which you insert elements into a
list is preserved, allowing indexed access and modifications. This characteristic is
useful for tasks like sorting or when the sequence has semantic meaning, like storing
monthly sales data.

• Tuple: Tuples, like lists, are ordered. Even though they're immutable, the sequence
they're declared in remains consistent.

• Set: A set doesn't retain any specific order. It’s designed for membership tests,
making it optimal for scenarios where insertion order isn't significant but ensuring
uniqueness is.
• Dictionary: In versions prior to Python 3.7, dictionaries didn't guarantee order.
However, from Python 3.7 onwards, dictionaries maintain the order of items based
on their insertion. This ensures a predictable mapping, beneficial for operations like
serialization.

3. Duplicate Handling

How a data structure handles duplicates often determines its utility in particular scenarios.

• List: Lists don't discriminate against duplicate values. They're accommodating


structures that will store as many identical elements as you insert, which is handy for
collections where occurrences matter.

• Tuple: Tuples also permit duplicates, offering another avenue for ordered,
immutable storage.

• Set: Sets stand out by not allowing any duplicate values. This inherent property
assists in creating collections of unique items, which can be beneficial for operations
like union, intersection, and difference.

• Dictionary: While dictionaries allow duplicate values, their keys must be unique. This
ensures a one-to-one mapping between keys and values.

4. Data Structure Representation

Understanding how each structure is represented syntactically can accelerate coding speed
and reduce errors.

• List: Denoted by square brackets. e.g., [1, 2, 3]

• Tuple: Encapsulated within parentheses. e.g., (1, 2, 3)

• Set: Defined using curly brackets without key-value pairs. e.g., {1, 2, 3}

• Dictionary: Illustrated using curly brackets with distinct key-value pairs. e.g., {'a':1,
'b':2, 'c':3}

For a streamlined understanding, consider the following table:


Aspect list tuple set dictionary

Mutable? Yes No Yes Yes

Ordered? Yes Yes No No

Allows
Yes Yes No Yes (Values)
Duplicates?

Can be a Mathematical Key-Value


Unique Feature -
dictionary key operations pairs

[1, 2, {'a':1, 'b':2,


Representation (1, 2, 3) {1, 2, 3}
3] 'c':3}

When developing Python applications, this differentiation becomes pivotal. It ensures that
the right structure is harnessed for the task, optimizing both performance and data
integrity.

4. What are lists? What is a list in Python? How to create


nested lists? Demonstrate how to create and print a 3-
dimensional matrix with lists. What is list
comprehension? Explain with at least 3 different
examples.
A Python list is a collection of zero or more elements. An element of the list can be
any data. It can be string, numerical, or a combination of both types. A list in Python
is like an array in C or Java. Lists are mutable- that is, you can change their content-
and they have many useful specialized methods.

How to Create a Python List?

A Python list is created by adding elements in the square brackets [ ].

For example:
num = [1, 2, 3, 4]

letter = [‘a’, ‘b’, ‘c’, ‘d’]

Fig: Create the Python List

These lists can contain elements of different types.

Creating a Python List

A list is created in PythonPython by placing items inside [], separated by commas. A


list can have any number of things; they can be of different types (integer, float,
string, etc.).

1. Access in Python list: Each item in a list is related to a number. The number is
known as the list index. It accesses elements of an array using the index number
(0, 1, 2, 3 …).

2. Negative Indexing in PythonPython: Python allows negative indexing for


sequences. If the specified index does not, it shows the "Index Error" exception.

3. Slicing in Python list: In Python, it is possible to access a section of items from


the List using the slicing operator ":" not just a single item.

Just note that when we slice lists, the start index is inclusive, but the end index is
exclusive.

Access Elements From List


Every Python list starts with the index ‘0’. We can access the elements by specifying
the index number. For example: To access elements in the list, we provide the index
(as integer) inside the square brackets ( [ ] ) as given below.

Fig: Access elements from starting of the list

To access the elements from the end we use negative indexing. -1 means the last
element. -2 the second last element and so on. For instance, if you want to access
the 4th element from the ending of the list named mix, you write mix[-4].

Fig: Access the elements from ending of the list

You can also access the elements from a specific range. To get elements from index
1 to index 3 from the list mix, you should write mix[1:4].

Fig: Access the elements from a specific range

Remember that the first item is position 0.

Note: The search will start at index 1 (included) and end at index 4 (not included)
If the starting value is left out, the range will begin from the starting element. For
instance:

Fig: Get elements from Index 0

Change and Add Elements to the List

In a Python list, the element value can be changed by specifying the index number
and replacing it with a new value. For instance:

Fig: To change the element in Python List

For adding new elements to a list in Python, you can use the ‘append ()’ method or
‘insert ()’ method.

1. Using the Append() Method

The append() method adds the element to the end of the list. For example:
Fig: Adding element by using append () method

2. Using the Insert() Method

If you want to insert an element at a specific index, you should use the insert ()
method.

For instance:

Fig: Add element using insert() method

Delete Elements From a List

There are two ways of removing elements from a list:

1. Delete Specified Elements We Use Remove() Method.

Suppose you want to delete the item “get” from the list “mix”. We write it as
mix.remove(“get”).

Fig: To delete element by using remove()


2. To Remove the Element From Specific Index We Use
Del() Method

Syntax: del list_name [index]

Fig: Deleting element using the del() method

Check if the Item Exists in List

You can check if the particular element exists in the list or not. The following
example can be used to perform the same:

Fig: Check if the item exists in the list

Check the Length of the List

You can check the number of items in the list by using ‘len ()’ method
Fig: To check the number of items in the list

To Join the Two List

There are several ways to join two lists, and the easiest method is to use the ‘ + ‘
operator. This can be done in the following way:

Fig: Join two Python lists

Updating List in Python

There are different ways to update a Python list, and we can use any of them for
updation. The Python list offers various methods for altering data.

• List.append (value) Append a value: If you like to add a single element to the
python list, then List.append(value) is the best fit for you. The List.append(value)
always adds the value to the end of the existing List.
• List.extend(iterable) Append a series of values: The append and extend methods
have a similar purpose of adding data at the end of a list. The contrast lies in the
fact that the append method incorporates a solitary element to the conclusion of
the List. In contrast, the extend method appends a series of elements from a
collection or iterable.

• List.insert(index, value) At index, insert value: The insert() method is similar to the
append() method; however, the insert method inserts the value at the given index
position, whereas append() always adds the element at the end of the List.

• List.remove(value) Remove the first instance of value: The remove(value) method


removes the first occurrence of the given value from the List. There must be one
occurrence of the provided value; otherwise, the PythonPython raises ValueError.

• List.clear() # Remove all elements: The clear() method is used to remove all the
elements from the List. We can also perform the same action with del List [:] in a
similar manner.

List Items in Python

List items are of different types; those can be ordered, changeable and allow
duplicate values.

• Ordered List: When the List is ordered, the items are in a defined order, and the
order doesn't change if new items are added to the List; the new items are placed
at the end. Note: Some list methods will change the order, but generally, the order
of the items will not change.

• Changeable: The lists are changeable, meaning we can either change, add,
or remove items in a list after it has been created. Allow Duplicates-Since
lists are indexed in Python, lists can have items with the same value.

• List Items: Data Types: List items are of any data type like string, int or
boolean, etc.
• Type(): Lists are defined as objects with the data type 'list'; text added with this
type will be considered a list in PythonPython.

• The List() Constructor: It is possible to use the List () constructor when we create
a new list; any data type can be used for creating a list with it.

• Python Collections (Arrays): There are four collection data types in the
PythonPython as follows :

1. List: A List is a type of collection that is arranged in a specific order and


can be modified. Additionally, it permits the inclusion of duplicate
items.

2. Tuple: A tuple is an ordered and immutable collection of elements.

3. Set: is an unordered, unchangeable*, and an unindexed collection. No


duplicate members.

4. Dictionary: is a collection that is ordered** and changeable. There are


no duplicate members.

Iterating a List in Python

There are six ways with which we can iterate a list in PythonPython.

1. Using Loop: The easiest way to iterate Lists in programming is by using them for a
loop.

2. Using Loop and Range() Function: This method to iterate the List while
programming uses the loop and range() function together. Iterating the List
utilizing this method is not recommended if iteration using a for loop is possible.

3. Using While Loop: we can also iterate the List in PythonPython using a while loop.

4. Using List Comprehension: This is the most robust method for iterating the List
while programming in Python.

5. Using Enumerate() Function: You may need to display the element's index and the
element in the List itself a few times. We use the enumerate() function for the List
iteration in such cases.
6. Using Numpy Function: Methods that have been discussed till now are preferable
for small or single-dimensional lists. But n-dimensional lists are advised to use an
external library like Numpy for iterating lists.

FOR and IN Loops in Python

A FOR loop is used for iterating in a sequence (a list, a tuple, a dictionary, a set, or a
string); it's not like FOR keyword in other programming languages and acts like an
iterator method, as found in other object-oriented languages. With FOR loop, we can
execute a set of statements once in a list, tuple, set, etc. FOR loop does not require
indexing variables to assess beforehand.

• Looping through String: strings are iterable objects containing a sequence of


characters.

• The Break Statement: Break statement stops the loop before it has looped
throughout all the items.

• The Continue Statement: Continue statement stops the current iteration of loop
and continues with the next.

• The Range Function: Looping through a set of code specified number of times, we
can use the Range() function; it gives a series of numbers that starts from 0,
increments by 1, and ends at a specified number. Range() function gives 0 as a
starting value. RANGE(2,6) means values from 2 to 6 but not 6.

• Else IN FOR Loop: The Else keyword in a FOR loop specifies a code block
executed when the loop is finished.

• Nested Loop: It is a loop inside a loop element. The "inner loop" can be executed
once for each iteration of the "outer loop."

• The Pass Statements: FOR loops cannot be empty, but for some reason, have a
FOR loop with no content; put in the Pass statement to avoid getting an error.

Python List Comprehension


• List Comprehension: List comprehension gives a shorter syntax when we want to
create a new list for the values of an existing list.

• The Syntax: The return value is a new list, leaving the old List unchanged.

• The Condition: The condition is like a filter that only accepts the items evaluated
as TRUE and is optional.

• Iterable: An iterable is any object that can be iterated over, such as a list, tuple, or
set.

• Expression: The expression is the current item in the iteration, but it is the
outcome, which can be manipulated before it ends up like a list item in the new
List.

Taking Input from a Python List

To accept input from the user in PythonPython, we can use the input() function.
When used, it enables the programmer to get a string, integer, or even a character as
input from the user. But the approach we follow is slightly different when accepting a
list as input.

Complexities for Various Functions and Elements in List

For all the data consumed and generated every day, algorithms should be good
enough to handle operations in large volumes of data.

1. Computational Complexity: Computational complexity is a field of computer


science that analyzes algorithms based on the number of resources required to
run them. The amount of necessary resources based on the input size and
complexity is expressed as a function of n, where n is the input size.

2. Time Complexity: When analyzing the time complexity of an algorithm, there can
be three cases: best-case, average-case, and worst-case.
1. Best Case: It solves the problem for best input.

2. Average Case: This is the average complexity of solving the problem.

3. Worst Case: The complexity of solving problems for the worst input of
size n.

3. Big-O Notations: Big-O notation, also called "asymptotic notation," is a


mathematical notation that signifies the limiting behavior of any function when
the argument goes towards a particular value or infinity.

Reversing a List in Python

Various built-in functions are available to reverse a list in PythonPython. But


choosing which to use for the specific problem needs to be clarified.

• Using Reverse() Method: There is an in-built method known as Reverse() in


Python, which can reverse the List by changing elements in the original List. This
method can be used in conditions where memory efficiency is required.

• Using Reversed() Method: This is a built-in function to reverse list elements


without creating copies or modifying the original List. It also creates an iterator
and stores the details.

• Using Slicing Operation: A slicing operation is performed to access the list


elements from a starting-to-end index. The slicing operation can help reverse the
List in Python.

• Using Recursion: The List can be reversed by recursion without built-in functions.

Built-in Functions In Python List

Python consists of some in-built functions that we can use.


Function Description

clear() Removes all the elements from the list

copy() Returns a copy of the list

append() Adds an element to the end of the list

insert() Add an element to the specified position

Removes the element from the specified


pop()
position

Removes the item with the specified


remove()
value
reverse() Reverses the order of the list

Returns the number of elements with the


count()
specified value

Returns the index of an element in the


index()
list

Here are some examples of the functions that are mentioned in the table:

1. Clear()

The clear() function removes all the elements from the list.

Syntax: mix.clear()

Fig: Clear a Python list

2. Copy()

The copy() function returns a copy of all the items in a list.

Syntax: new_list = mix.copy()


Fig: Copy one Python list to another list

3. Reverse()

The reverse method prints the items in a list in the reverse order.

Syntax: list.reverse()

Fig: Reverse a Python List

4. Index()

The index method returns the index of the specified item in a list.

Syntax: list.index(element)

Fig: Find the index in a list


5. What are generators in Python?
• Generators in Python are a special type of iterable that allow you to iterate over a
sequence of values without necessarily storing them in memory all at once.
• They are implemented using functions and the `yield` keyword.
• When a generator function is called, it returns a generator object, which can be
iterated over using a loop, comprehension, or passed to a function that consumes
iterables (like `list()` or `sum()`).
• Here's a simple example of a generator function:
Program:
def count_up_to(limit):
count = 1
while count <= limit:
yield count
count += 1
# Using the generator
counter = count_up_to(5)
for number in counter:
print(number)
output:
1
2
3
4
5

• In this example, `count_up_to()` is a generator function. Instead of using `return` to


return a value, it uses `yield`. This allows the function to yield values one at a time
when it's called. When you iterate over the generator object `counter`, it generates
the values from 1 to 5, one at a time, printing each value as it's generated.
• Generators are particularly useful when dealing with large sequences of data, as they
allow you to work with one element at a time without having to store the entire
sequence in memory. This makes them more memory efficient compared to creating
lists or other data structures containing the entire sequence.

• Another benefit of generators is that they allow for lazy evaluation. This means that
values are generated on-the-fly as they are needed, rather than generating all values
upfront. This can lead to significant performance improvements in situations where
not all values are needed or when dealing with infinite sequences.

• Python also provides generator expressions, which are similar to list comprehensions
but produce generator objects instead of lists. They follow the syntax of list
comprehensions, but use parentheses `()` instead of square brackets `[]`.
Example:
# Generator expression example
squares = (x * x for x in range(10))
for square in squares:
print(square)

Generators are a powerful feature of Python, providing a concise and memory-efficient way
to work with sequences of data, especially when dealing with large datasets or infinite
sequences.

6. Discuss about tuples in Python. What is a tuple? How


literals of type tuple are written? Explain about built-in
functions of tuple. What is a tuple? How literals of type
tuple are written?
Tuples in python is one of the four inbuilt data types used to store collections in Python.
Unlike other data types, the elements in tuples are ordered and immutable. They are used to
store multiple items in a single variable and provides some built-in operation to work with
them.
Creating a Tuple in Python:
Tuples in Python can only be created when they are being assigned, hence placing all the
elements inside the parenthesis, separated by a comma will create a tuple. Let’s take a
closer look at the syntax:
tempTuple = ('apple', 'mango', 'banana')
print(tempTuple)
Output
('apple', 'mango', 'banana')
The parenthesis in the above syntax are optional and hence a tuple can also be created
without writing the parenthesis. But remember it’s always a good practice to have the
parenthesis, as it always increases the code readability and understanding.
The above snippet can also be written as:
tempTuple = 'apple', 'mango', 'banana'
print(tempTuple)
Output
('apple', 'mango', 'banana')
Immutable in Tuples:
Tuples in Python are similar to lists but with a key difference: they are immutable. This
means once a tuple is created, its elements cannot be changed, added, or removed. Let's
break down some characteristics of tuples:
Immutable Nature:
Once a tuple is created, its elements cannot be modified. This ensures data integrity and
stability.
Ordered Collection:
Like lists, tuples maintain the order of elements as they are inserted.
Support for Duplicate Values: Tuples allow duplicate values just like lists.
Accessing Elements:
Elements in a tuple can be accessed using their index values. Here's an example illustrating
the immutability of tuples in python:
my_tuple = (1, 2, 3)
#Attempting to change an element in the tuple will result in an error
my_tuple[1] = 1 # This will raise a TypeError
When attempting to modify an element within a tuple, Python will raise a TypeError because
tuples in python do not support item assignment due to their immutable nature. This
constraint ensures that once data is stored in a tuple, it remains unchanged throughout the
program's execution.
Python Tuple Types:
Python offers two primary types of tuples: named tuples and unnamed tuples.
Named tuples:
created by subclassing the tuple class and assigning a name to the new class, serve well for
representing structured data like records, akin to database entries. Each element within a
named tuple corresponds to a field in the record, permitting access by name instead of
index. For instance:
class MyTuple(tuple):
pass
my_tuple = MyTuple(("one", "two", "three"))
print(my_tuple.one)
Outputs:
one
Unnamed Tuples:
are more prevalent and are generated simply by separating values with commas. They are
suitable for storing unstructured data that doesn't necessitate naming. Here's an example:
my_tuple = (1, 2, 3)
print(my_tuple)
Outputs
(1, 2, 3)
In this instance, a tuple in python containing three elements is created. Accessing elements
within the tuple can be achieved using index notation, akin to how one would interact with a
list.
Accessing Elements in a Python Tuple and Indexing:
Accessing elements in a tuple is no different then accessing elements in a list. As python
follows 0 based indexing hence a tuple with n elements will have indices from 0 through n-1.
An index in a tuple is accessed with the index operator [ ]. For example:
Let’s consider a basic tuple:
tempTuple = ('hello', 1, 2, 3)
print(tempTuple[0]) # prints first element of the tuple
print(tempTuple[3]) # prints last element of the tuple
print(tempTuple[4]) # error
Nested Python Tuple Accessibility
nestedTuple = ('hello', [1 ,2, 3], (4, 5, 6))
print(nestedTuple[0][2])
print(nestedTuple[2][2])
Accessing Via Negative Indices:
Python allows you to access elements of a collection via negative indices. When accessing
using a negative index, -1 depicts the last element and -n depicts the first index where n is
the length of the index.
Consider the following mapping of positive index with negative index:

tempTuple = ('Welcome', 'to', 'interview', 'bit.', 'Have', 'a', 'great', 'day')


print(tempTuple[2]) # interview
print(tempTuple[-6]) # interview

Updating Tuples in Python:


Adding a new element or deleting one is not really an option when dealing with tuples in
python, as they are immutable. Even the elements of the tuple cannot be updated until and
unless the element is mutable for example a list.
Let’s take an example
tempTuple = ('Welcome', 'to', 'interview', 'bit.', 'Have', 'a', 'great', 'day', [1, 2, 3])
# tempTuple[0] = 'Hello' # throws type error, tuple object does not support type assignment.
tempTuple[8].append(4) # appending a new integer i.e. 4 in a list at 8th index of the tuple
‘tempTuple’
# Printing the list at 8th index in the tuple
print(tempTuple[8]) # OUTPUT: [1, 2, 3, 4]
tempTuple[8].pop(3) # popping element at 3rd index from the list i.e. 8th index of the tuple
'tempTuple'
# Printing the list at 8th index in the tuple
print(tempTuple[8]) # OUTPUT: [1, 2, 3]
tempTuple = (1, 2, 3) # Assigning tuple all over again
# Printing the tuple
print(tempTuple) # OUTPUT: (1, 2, 3)
Output
[1,2,3,4]
[1,2,3]
(1,2,3)

• Tuples in python can definitely be reassigned, which is very different from updating a
tuple. Reassigning a tuple is redefining the tuple all over again.
• Just like strings, we can also concat two or more tuples to form a new tuple
using ‘+’ operation or apply repetition on a tuple using ‘*’ operator, just the result
here is a python tuple and not a string.
# concatenating two different tuples
print(('apple', 'mango') + (1, 2, 3)) # OUTPUT: (‘apple’, ‘mango’, 1, 2, 3)
# repeat a tuple 5 times
print(("apple",) * 5) # OUTPUT: (‘apple’, ‘apple’, ‘apple’, ‘apple’, ‘apple’)
Output:
('apple', 'mango', 1, 2, 3)
('apple', 'apple', 'apple', 'apple', 'apple')

In-built Functions for Tuple


Python has the following inbuilt functions to offer for tuples:

Different Operations Related to Tuples:


Concatenation:
We will use plus operators(+) to Concatenation of Python Tuples.
tempTuple = ('apple', 'mango')
result = tempTuple + (1, 2, 3) # concatenating two different tuples
print('concatenation of a tuple', result)
# OUTPUT: concatenation of a tuple (‘apple’, ‘mango’, 1, 2, 3)
Nesting:
We can do the nesting of tuples means a tuple inside another tuple.```
# Code for creating nested tuples
tup1 = ('a','b','c')
tup2 = ('d','e')
tup3 = (tup1, tup2)
print(tup3)
#(('a','b','c'), ('d','e'))
Repetition:
We have the ability to form a tuple containing multiple identical elements by duplicating a
single element within that tuple.
tup = ('2',)*3
print(tup)
#output: ('2','2','2')

Slicing:
Slicing in tuples works the same as it works for a String slicing or any other sequence of
elements. Slice is an operator that allows you to fetch a sub collection (in this case a sub
tuple) from a collection by slicing it from a start index and a stop index.
Slice syntax:
tuple[start : stop : step]
start: is the starting index of the string, on which slicing operation has to be performed. It
determines from where slicing of the string will ‘begin’.
stop: is the stopping index of the slicing, ‘until’ which slicing operation has to be performed
i.e stop index is excluded while generating the sub-tuple.
step: It is an optional argument that defines the steps when iterating the list i.e. it allows us
to skip over elements.
Consider the above figure when understanding the following code snippet
temptuple = ("Welcome", "to", "interview", "bit.", "Have", "a", "great", "day")
tuple1 = temptuple[::] # fetching complete tuple
print("tuple1:", tuple1) # OUTPUT: (‘Welcome’, ‘to’, ‘interview’, ‘bit.’, ‘Have’, ‘a’, ‘great’, ‘day’)
tuple2 = temptuple[0 : 6] # fetching tuple from 0th index to 6th index
print("tuple2:", tuple2) # OUTPUT: (‘Welcome’, ‘to’, ‘interview’, ‘bit.’, ‘Have’, ‘a’)
tuple3 = temptuple[:: 3] # jumping every third element from start to end
print("tuple3:", tuple3) # OUTPUT: (‘Welcome’, ‘bit.’, ‘great’)
tuple4 = temptuple[1:5:2] # jumping to every 2nd element starting from 1st index until 5th
index
print("tuple4:", tuple4) # OUTPUT: (‘to’, ‘bit.’)
tuple5 = temptuple[-8:-5] # 8th index from end to 5th index from end
print("tuple5:", tuple5) # OUTPUT: (‘Welcome’, ‘to’, ‘interview’)
tuple6 = temptuple[::-3] # jumping every 3rd element in reverse
print("tuple6:", tuple6) # OUTPUT: (‘day’, ‘Have’, ‘to’)
tuple7 = temptuple[-7:-3:2] # alternate implementation of tuple4
print("tuple7:", tuple7) # OUTPUT: (‘to’, ‘bit.’)

Output
tuple1: ('Welcome', 'to', 'interview', 'bit.', 'Have', 'a', 'great', 'day')
tuple2: ('Welcome', 'to', 'interview', 'bit.', 'Have', 'a')
tuple3: ('Welcome', 'bit.', 'great')
tuple4: ('to', 'bit.')
tuple5: ('Welcome', 'to', 'interview')
tuple6: ('day', 'Have', 'to')
tuple7: ('to', 'bit.')
Deleting:
As discussed, python tuples being immutable cannot be updated. Hence once some values
are assigned to a tuple, it cannot be deleted. You can delete a tuple as a whole, but deleting
a specific value/element in a tuple is not possible.
tempTuple = (1, 2, 3, 4, 5)
# tempTuple.pop() # throws error as object has no attribute pop
# del tempTuple[3] # throws error as tuple does not support object deletion
print(tempTuple) # OUTPUT: (1, 2, 3, 4, 5)
del tempTuple
print(tempTuple) # throws NameError: name 'tempTuple' is not defined
Output:
(1,2,3,4,5)
Traceback (most recent call last):
File "main.py", line 6, in <module>
print(tempTuple) # throws NameError: name 'tempTuple' is not defined
NameError: name 'tempTuple' is not defined
Finding the length:
In Python, determining the length of a tuple can be accomplished using the built-in function
len(). Simply provide the tuple as an argument to len(). This will return the number of
elements contained within the tuple.
tup = (1,2)
print(len(tup))
#Output: 2
Multiple Data Types with tuples:
Tuples in Python are versatile containers, allowing you to store elements of different data
types within the same tuple.
temp = ("a",True,2)
print(temp)
#Output: ('a',True,2)
Conversion of lists to tuples:
In Python, you can transform a list into a tuple effortlessly by utilizing the tuple()
constructor and providing the list as its argument.
list1 = [1, 2, 3]
print(tuple(list1))
#Output: (1, 2, 3)

Tuples in a Loop:
We can also create a tuple with a single element in it using loops.
temp = ('a',)
n=2
for i in range(int(n)):
temp = (temp,)
print(temp)
Output:
(('a',),)
((('a',),),)
Advantages and Disadvantages of Tuple in Python:
Advantages:

• Tuples being immutable, turns out to be a write-protected collection. Tuples can be


of advantage when we want to store some secure read only data that we cannot
afford to be changed throughout our code.
• Tuples can store data of multiple data types, that makes them a heterogeneous
collection.
• Tuple being a readonly collection, has a faster iteration. (As they are stored in a single
block of memory, and don’t have extra space for storing objects, they have constant
set of values)
Disadvantages:

• Tuple’s being write protected, is an advantage but also a disadvantage as it cannot be


used when we want to add or delete a specific element. Hence has a limited use
case.
• Syntactically less readable as, tuples can be created by either adding parentheses or
by not providing them incase we have more than one element. But not using
parentheses in case of one element, will not create a tuple and hence a trailing
comma in such case is required. This can makes code readability a bit complex for
some.
• As tuple is a class, it's stored on the heap and is overhead on the garbage collector.
• Tuple’s advantages and disadvantages are nothing but its use cases i.e. tuple serves
some use cases hence one should know when to use tuple, in order to use it for their
advantage. Tuples when used where a list or a dictionary or a set would’ve been
used, will turn out to be a disadvantage.

7. Write a python script to print the following pattern


****
***
**
*
Program:

def print_pattern(rows):

for i in range(rows, 0, -1):


# Print spaces

for j in range(rows - i):

print(" ", end="")

# Print asterisks

for k in range(i):

print("*", end="")

print()

# Define the number of rows

rows = 4

print_pattern(rows)

output:
****

***

**

8. Write a short note on Python sets?


Introduction to Python Sets:

• Python set is a built-in data type of Python that stores data in the form of multiple
items in a single variable.
• Each of the elements added will be unique, we can modify them after creating the
set, and it doesn’t have an index number assigned to it. Hence we cannot access the
elements just by using the index number.
• The syntax contains a set name that is usually assigned to the set of data or elements
enclosed between the curly parenthesis and separated by a delimiter, that is, a
comma. Or you can also use the set() method.
Syntax:
variable_name = {"string", value, number}
Or
variable_name = set([value, value, value])
Example:
firstset = {"Johnny", "Paul", "Kevin"}
print(firstset)

• Here, the first set is the variable name in which the set is stored. The curly braces {}
represent the set, and since we are adding string values, double/single inverted
commas are necessarily required. Commas separate the values in the set. Now, since
we have seen the syntax of the set with an example in Python, let us discuss the
different methods used in Python sets.
Key Highlights:

• A Python set is similar to a mathematical set with additional conditions.


• A Python set is immutable, doesn’t contain duplicate values, and has no index
assigned to each value like other collections.
• You can easily create the set by passing the immutable elements in curly braces. Here
each of the elements separates with a comma.
• We can perform mathematical operations like intersection, union, difference,
accessing the elements, and modifying the set.
Create Sets in Python:
To create sets in Python, place all the elements within curly braces {}, separated by commas.
A set can include unlimited items, such as integers, floats, tuples, and strings. However,
mutable elements such as lists, sets, and dictionaries cannot be used as elements within a
set.
1. Using Set Constructor:
Certainly! Here’s an example that demonstrates the creation of a set in Python using the
set() constructor:
my_set = set("EDUCBA")
print(my_set)
We create a set my_set by passing a string “EDUCBA” to the set() constructor. The
constructor treats the string as an iterable and creates a set with individual characters as
elements.
Output:
{'U', 'B', 'C', 'D', 'A', 'E'}

2. Using Curly Braces:


Code:
# create a set of integer type
employee_id = {12, 14, 16, 18}
print('Employee_ID:', employee_id)
# create a set of string type
vowels = {'a', 'e', 'i', 'o', 'u'}
print('Vowel Letters:', vowels)
# create a set of mixed data types
mixed_set = {'Hello', 1, -1}
print('Set of mixed data types:', mixed_set)
Output:
Employee_ID: {16, 18, 12, 14}
Vowel Letters: {'a', 'i', 'e', 'o', 'u'}
Set of mixed data types: {1, 'Hello', -1}

Set Operations in Python:


Below are the different set operations used in Python:
1. Set Union:
It is a function that returns a set with all elements of the original set and the specified sets.
Since it returns a set, all items will have only one appearance. The item will appear only once
if two sets contain the same value.
Code:
A1= {24, 35, 34, 45}
A2= {24, 56, 35, 46}
A3= {24, 35, 47, 56}
print(A1.union(A2, A3))
Output:
{34, 35, 45, 46, 47, 24, 56}

In the above screenshot, you can see the code output on execution. If you look closely, you
will find all values from A1 and all unique values from the other two sets.

2. Set Intersection:
It is very different from the previous method’s built-in set. In this case, only the elements
common in both sets or multiple sets (in case of more than two sets) are usually returned as
a set. Now let us go through an example.
Code:
A1= {24, 35, 34, 45}
A2= {24, 56, 35, 46}
A3= {24, 35, 47, 56}
print(A1.intersection(A2, A3))
Output:
{24, 35}

As you can see, the three sets only had two elements in common which are 24 and 35.
Hence, executing the code returned a set containing only 24 and 35.
3. Set Difference:
This is a very important function inset. This function returns a set which is the difference
between two sets. Remember that here difference does not mean subtraction because it is
the difference between the number of elements in two sets and not the values of elements.
For example, set A1 – set A2 means it returns a set with elements present in A1 but not in
A2, and vice versa in the case of set A2 – set A1 (present in A2 but not in A1). An explanation
of the same is below with the help of an example.
Code:
A1= {24, 35, 34, 45}
A2= {24, 56, 35, 46}
print(A1.difference(A2))
print(A2.difference(A1))
Output:
{34, 45}
{56, 46}
In the above screenshot, if you look carefully, there is a difference between the first and
second results. The first result shows the elements in A but not B, whereas the second
shows elements present in B but not A.
4. Symmetric Difference:
The symmetric difference of the two sets method removes the same element in both sets.
You can calculate it using the ^ symbol or symmetric_difference().
Code:
#First set of elements
first_list = {20, 30, 40, 50, 60}
#Second set of elements
second_list = {50, 60, 70, 80, 90}
#Using symmetric difference() method
final_result = first_list.symmetric_difference(second_list)
print("\nFinal set of elements:")
print(final_result)
Output:
Final set of elements:
{80, 20, 70, 40, 90, 30}

Set Methods:
Now let’s see methods related to the set:
1. add():
As the name suggests, it is generally used to add a new element to the set, which means you
are increasing the number of elements set by one. Here one very important piece of
knowledge about the set is that the element only add if it is not already present in the set
assets; do not take duplicate elements. The add method also does not return any value. Let
us give an example.
Code:
firstset = {"Ryan", "Edward", "Gary"}
firstset.add("Larry")
print("The new word is",firstset)
#to check the duplicate property of Set
firstset.add("Larry")
print("The new word is",firstset)
Output:
The new word is {'Larry', 'Gary', 'Ryan', 'Edward'}
The new word is {'Larry', 'Gary', 'Ryan', 'Edward'}

If you see the output the first time when add() function is generally used, it adds the
element, and the size of the set is increased by one, as shown when we execute the first
print statement, but the second time when we use add() method to add the very same
element (Larry) like the first time when executing the print statement, we see the same
elements getting displayed with no increase in the size of the set which means that set does
not any take duplicate values.
2. update():
You have seen add() method to add the elements into the set. But the only downside about
add() method is you can only add an element to the set at a time. Hence update() method
comes to the rescue, which helps you add multiple elements simultaneously.
Code:
first_set = set([1, 2, 3, 4, 5])
print("The first set",first_set)
first_set.add(6)
print("Final set",first_set)
Output:
The first set {1, 2, 3, 4, 5}
Final set {1, 2, 3, 4, 5, 6}

3. remove():
This function is to remove elements from the set. The elements you need to remove pass as
arguments. The function removes the element if present in the set; otherwise, it returns an
error. We will execute an example to check this.
Code:
firstset = {"Tyler", "Scott", "Jack"}
firstset.remove("Scott")
print(firstset)
# to check the error
firstset.remove("Henry")
Output:
{'Jack', 'Tyler'}
ERROR!
Traceback (most recent call last):
File "<main.py>", line 8, in <module>
KeyError: 'Henry'

If you see the screenshot above, when the code is generally executed, it removes the
element “Scott” as it was present in the set, but when we try to remove” Henry”, it gives us
an error as “Henry” is not present in the set.
4. discard():
This built-in method also removes elements from the set but differs from the remove
method we discussed earlier. If the element is present in the set, it removes the element,
but if it is present, it returns no error and normally prints the set. We will see an example of
this.
Code:
firstset = {"Tyler", "Scott", "Jack"}
firstset.discard("Jack")
print(firstset)
firstset.discard("Henry")
print(firstset)
Output:
{'Scott', 'Tyler'}
{'Scott', 'Tyler'}

5. clear():
As the name suggests, it removes all the elements from the set. It neither takes any
parameter nor does it return any value. We have to call the clear method and execute it. Let
us look at an example:
Code:
firstset = {"Tyler", "Scott", "Jack"}
print("Before clear",firstset)
firstset.clear()
print("After clear",firstset)
Output:
Before clear {'Tyler', 'Jack', 'Scott'}
After clear set()

So, the above screenshot shows that before we had executed the clear method, the list
prints with elements, and then when we executed the clear() method, all the elements get
easily removed. We are only left with an empty set.
6. pop()
The pop() method generally removes an item from the set. It will always aim at removing the
last element from the set. If the set has unordered items, then any items from the list are
used.
Code:
list_of_days = {"Monday", "Sunday", "Tuesday", "Wednesday", "Friday"}
print("\nList of Days:")
print(list_of_days)
# Let’s use the pop() method to remove the element from the set
list_of_days.pop()
# Now print the modified set
print("\nModified set:")
print(list_of_days)
Output:
List of Days:
{'Monday', 'Friday', 'Tuesday', 'Sunday', 'Wednesday'}
Modified set:
{'Friday', 'Tuesday', 'Sunday', 'Wednesday'}

The set is ordinarily unordered, so it removed Wednesday from the list.


7. copy()
This method is to create a shallow copy of a set. The term shallow copy means that if you
add new elements in the set or remove elements from the set, the original set does not
change. It is the basic advantage of using the copy function. We will see an example to
understand the shallow copy concept.
Code:
Veggie_set = {"Drumstick","Broccoli","Mushroom"}
new_set = Veggie_set.copy()
print(new_set)
Output:
{'Drumstick', 'Broccoli', 'Mushroom'}

8. difference()
Code:
Fruit_set1 = {"Apple","Guava","Cherry"}
Fruit_set2 = {"Plump","Blueberry","Guava"}
New_set = Fruit_set1.difference(Fruit_set2)
print(New_set)
Output:
{'Apple', 'Cherry'}

As one can notice, “Guava” has been removed. The same can be done the other way:

Code:
Fruit_set1 = {"Apple","Guava","Cherry"}
Fruit_set2 = {"Plump","Blueberry","Guava"}
New_set = Fruit_set2.difference(Fruit_set1)
print(New_set)
Output:

The same element present in both, i.e., “Guava”, has been removed.
9. intersection()
This method helps in finding the common elements among more than two sets.
Syntax:
set1.intersection(set2, set3 ...etc.)
More than one set can be put in the parameters of the intersection.
Code:
Flowers_set1 = {"Rose","Lotus","Lilly"}
print(Flowers_set1)
Flowers_set2 = {"Lotus","Tulip","Rose"}
print(Flowers_set2)
New_set = Flowers_set1.intersection(Flowers_set2)
print(New_set)
Output:
{'Rose', 'Lotus', 'Lilly'}
{'Tulip', 'Lotus', 'Rose'}
{'Rose', 'Lotus'}

Code:
Flowers_set1 = {"Rose","Lotus","Lilly"}
print(Flowers_set1)
Flowers_set2 = {"Lotus","Tulip","Rose"}
print(Flowers_set2)
Flowers_set3 = {"Sunflower","Lotus","Jasmine"}
print(Flowers_set3)
New_set = Flowers_set1.intersection(Flowers_set2, Flowers_set3)
print(New_set)
Output:
{'Lotus', 'Rose', 'Lilly'}
{'Lotus', 'Rose', 'Tulip'}
{'Lotus', 'Sunflower', 'Jasmine'}
{'Lotus'}

10. Issubset()
This method helps you identify whether the set is a subset of others. The method issubset()
always returns the Boolean output. It will return “True” if all elements of one set exist in a
specified set; else, it will return “False.”
Code:
Animal_set1 = {"Tiger","Lion"}
print(Animal_set1)
Animal_set2 = {"Lion","Cheetah","Tiger"}
print(Animal_set2)
Eval = Animal_set1.issubset(Animal_set2)
print(Eval)
Output:
{'Tiger', 'Lion'}
{'Cheetah', 'Tiger', 'Lion'}
True

As one can notice, “Animal_set1” is part of “Animal_set2”. Hence issubset() method is


returning True.
11. issuperset()
This method helps you identify if elements of a set are part of other specified sets. This gives
output in the form of True or False.
Code:
Colors_set1 = {"Black","White"}
print(Colors_set1)
Colors_set2 = {"White","Black","Blue"}
print(Colors_set2)
check1 = Colors_set1.issuperset(Colors_set2)
print(check1)
check2 = Colors_set2.issuperset(Colors_set1)
print(check2)
Output:
{'White', 'Black'}
{'White', 'Black', 'Blue'}
False
True

12. symmetric_difference()
This method helps you find the elements that are part of sets but not common to both sets.
Code:
Birds_set1 = {"Bluebird","Oriole","Budgie"}
print(Birds_set1)
Birds_set2 = {"Finch","Bluebird","Weaver"}
print(Birds_set2)
check = Birds_set2.symmetric_difference(Birds_set1)
print(check)
Output:
{'Bluebird', 'Budgie', 'Oriole'}
{'Finch', 'Bluebird', 'Weaver'}
{'Oriole', 'Finch', 'Weaver', 'Budgie'}
13. union()
This method helps you unite elements from two sets. Both sets’ common and uncommon
elements are formed as a new set.
Code:
Sports_set1 = {"Cricket","FootBall","Basketball"}
print(Sports_set1)
Sports_set2 = {"Basketball","Tennis","Baseball"}
print(Sports_set2)
check = Sports_set2.union(Sports_set1)
print(check)
Output:
{'FootBall', 'Cricket', 'Basketball'}
{'Tennis', 'Baseball', 'Basketball'}
{'FootBall', 'Baseball', 'Cricket', 'Basketball', 'Tennis'}

14. isdisjoint()
This function returns a true value if it doesn’t contain any intersection values or doesn’t have
any common elements. If this condition is generally satisfied, then it returns true value. Else,
it will return false. Let’s understand it with an example,
Code:
A1 = {2, 3, 4}
A2 = {5, 6, 8}
print("\nWithout intersection of elements:")
print(A1.isdisjoint(A2))
A3 = {9, 1, 20}
A4 = {9, 1, 20}
print("\nWith intersection of elements:")
print(A4.isdisjoint(A3))
Output:
Without intersection of elements:
True
With intersection of elements:
False

FrozenSets in Python:
The frozen set is another built-in function of Python. It is similar to the normal set with a
uniqueness of immutable elements. Hence you cannot perform accessing or modifying
operations on a frozen set.
The elements of the frozen set cannot be changed after the creation. Modifying frozen sets’
contents is impossible using methods like add() or remove().
Creating a FrozenSet:
To create a frozenset object, you can use the frozenset() method. This method takes an
iterable sequence as input and returns a frozen set as the output.
Code:
my_set = {'a', 'b', 'c', 'd', 'e'}
fset = frozenset(my_set)
print(fset)
Output:
frozenset({'b', 'c', 'e', 'd', 'a'})

Now let’s check for immutable characteristics.


Code:
my_set = {'a', 'b', 'c', 'd', 'e'}
fset = frozenset(my_set)
print(fset)
fset.add('f')
Output:

Operations on FrozenSets:
Code:
# Frozensets
# initialize A and B
A = frozenset([10, 20, 30, 40])
B = frozenset([30, 40, 50, 60])
# copying a frozenset
C = A.copy()
print("\nPrinting set C:")
print(C)
# union
print("\nPrinting union of two sets:")
print(A.union(B))
# intersection
print("\nPrinting intersection of two sets:")
print(A.intersection(B))
# difference
print("\nPrinting difference of two sets:")
print(A.difference(B))
# symmetric_difference
print("\nPrinting symmetric difference of two sets:")
print(A.symmetric_difference(B))
Output:
Printing set C:
frozenset({40, 10, 20, 30})
Printing union of two sets:
frozenset({40, 10, 50, 20, 60, 30})
Printing intersection of two sets:
frozenset({40, 30})
Printing difference of two sets:
frozenset({10, 20})
Printing symmetric difference of two sets:
frozenset({10, 50, 20, 60})

Comparison of Set with Other Data Types:


1. Set vs List:

Set List

Python sets are unordered. Lists are Ordered.


Sets only store unique elements. Lists can contain duplicate elements.

Sets don’t allow to change or replace the elements. Changing parts is possible in Python lists.

2. Set vs Tuple:

Set Tuple

The set is Mutable. Tuple is Immutable.

Python sets are an unordered collection of Tuple is an ordered collection of items.


items.

Sets don’t allow to change or replace the Tuples also doesn’t allow to change or
elements. replace the elements.

3. Set vs Dictionary:

Set Dictionary

A set is a collection that has no specific A dictionary is a type of data collection


order. that stores information in key-value pairs
without any particular order.
Sets are mutable and have no duplicate Dictionaries are mutable, and keys do not
elements. allow duplicates.

Sets are represented in curly brackets. Dictionaries are enclosed in curly brackets
in the form of key-value pairs.

Sets Comprehensions in Python:


One powerful feature of Python sets is set comprehension, which allows you to create new
sets using a concise and expressive syntax. Set comprehension is similar to list
comprehension, but instead of creating a new list, it creates a new set.
Set comprehension uses a set of curly braces ({}) with an expression that defines the
contents of the new set. This expression can be combined with one or more for loops and/or
conditional statements to filter and transform the elements of the original set.
Example:
myList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
newSet = {element*3 for element in myList}
print("The existing list is:")
print(myList)
print("The Newly Created set is:")
print(newSet)
Output:
The existing list is: [1,2,3,4,5,6,7,8,9,10]
The Newly created set is: {3,6,9,12,15,18,21,24,27,30}

9. c = a << 240
# 240 = 1111 0000
print "Line 5 - Value of c is ", c
Predict the output of the above code?
ERROR!
Traceback (most recent call last):
File "<main.py>", line 5, in <module>
NameError: name 'a' is not defined

10. Write a short note on Python Dictionaries? Write a


short note on dictionary data type in Python? the Python
Dictionary Comprehension with examples. Write a
Python program that sorts a dictionary by its values.
Write a Python program that counts the number of
occurrences of a letter in a string, using dictionaries.

A dictionary is a kind of data structure that stores items in key-value pairs. A key is a unique
identifier for an item, and a value is the data associated with that key. Dictionaries often
store information such as words and definitions, but they can be used for much more.
Dictionaries are mutable in Python, which means they can be changed after they are
created. They are also unordered, indicating the items in a dictionary are not stored in any
particular order.

Creating a Dictionary

Dictionaries are created using curly braces {}. The key is on the left side of the colon (:) and
the value is on the right. A comma separates each key-value pair. Creating a Python
dictionary is straightforward. Remember to use curly braces {} and separate each key-value
pair with a comma.
You will use the built-in dictionary data type to create a Python dictionary. This type stores
all kinds of data, from integers to strings to lists. The dictionary data type is similar to a list
but uses keys instead of indexes to look up values.

You use the dict() function in Python to create a dictionary. This function takes two
arguments:

The first argument is a list of keys.

The second argument is a list of values.

Check out the example of how to create a dictionary using the dict() function:

# empty dictionary
my_dict = {}
# dictionary with integer keys
my_dict = {1: 'apple', 2: 'ball'}
# dictionary with mixed keys
my_dict = {'name': 'John', 1: [2, 4, 3]}
# using dict()
my_dict = dict({1:'apple', 2:'ball'})
# from sequence having each item as a pair
my_dict = dict([(1,'apple'), (2,'ball')])

Image Reference

Complexities for Creating a Dictionary

The time complexity of a dictionary is O(len(dict)); because a dictionary must be created, the
hash function must calculate the hash values for each element. O(N) is the space complexity
required to create a dictionary.
Changing and Adding Elements to a Dictionary

In Python, dictionaries are mutable data structures that allow you to store key-value pairs.
Dictionary can be created using the dict() constructor or curly braces' {}'. Once you have
created a dictionary, you can add, remove, or update elements using the methods
dict.update(), dict.pop(), and dict.popitem().

The `dict.update()` method is used to change an element in a dictionary. This method takes
a key and a value as arguments and assigns the value to the key. It will be added if the key
does not exist in the dictionary.

You can use the `dict.pop()` method to remove an element from a dictionary. This method
takes a key value as an argument and removes the key-value pair from the dictionary. In
case when key does not exist in the dictionary, `dict.pop()` will raise a `KeyError.`

The dict.popitem()` method is used to remove an arbitrary element from a dictionary, . This
method removes a random key-value pair from the dictionary and returns it as a tuple. If the
dictionary is empty, `dict.popitem()` will raise a `KeyError`.

Accessing Elements of a Dictionary

In Python, dictionaries are accessed by key, not by index. This means you can't access a
dictionary element by using its position in the dictionary. Instead, you must use the
dictionary key.

There are two ways to access a dictionary element in Python. The first is by using the get()
method. This method takes two arguments: the dictionary key and a default value. If the key
is in the dictionary, the get() method will return the value associated with that key. The get()
method will return the default value if the key is not in the dictionary.

The second way to access a dictionary element is using the [] operator. This operator takes
the dictionary key as an argument and returns the value associated with the key value. If the
key value is not in the dictionary, the [] operator will raise a KeyError.
# get vs [] for retrieving elements
my_dict = {'name': 'Jack', 'age': 26}
# Output: Jack
print(my_dict['name'])
# Output: 26
print(my_dict.get('age'))
# Trying to access keys that don't exist throws an error
# Output None
print(my_dict.get('address'))
# KeyError
print(my_dict['address'])

Methods:

In Python, several built-in methods allow us to manipulate dictionaries. These methods are
useful for adding, removing, and changing the values of dictionary keys. Dictionary methods
are a powerful way to work with dictionaries. By understanding how these methods work,
we can more effectively use dictionaries to store and manipulate data.

Method Description

Removes all the elements


clear()
from the dictionary
Returns a copy of the
copy()
dictionary

Returns specified key


get()
value

Returns an index having a


items() tuple for every key-value
pair

Returns a list containing


keys()
the dictionary's keys

Removes the element with


pop()
the specified key

Remove last inserted key-


popitem()
value pair

Returns specified key


value. If a key value does
setdefault()
not exist: insert the
specified value of key
Returns specified keys and
fromkeys()
values in dictionary

Updates the specified key-


update()
value pairs in dictionary

Returns values lists in the


values()
dictionary

Python Dictionary Comprehension

Dictionary comprehension is a feature that allows you to create a dictionary from a


list or another dictionary in a single line of code. It is a very concise way of creating
dictionaries and can be used to perform various operations on dictionaries. The
expression of Dictionary comprehension is (key: value) followed by a for statement
within the curly braces {}.

# Dictionary Comprehension

squares = {x: x*x for x in range(6)}

print(squares)

Dictionary Built-in Functions


Dictionaries have several built-in functions that allow you to perform various
operations on them. all(), any(), len(), cmp(), sorted(), etc. are the most common
dictionaries functions.

Function Description

The all() function in the


python dictionary
checks if all the keys in
the dictionary have
all() True as their values. If
all the values are True,
then it returns True.
Otherwise, it returns
False.

The any() function on


python dict checks if
any of the values in the
any() dict are True. If any of
the values are True, it
returns True, otherwise,
it returns False.

The cmp() function is


used to compare two
cmp()
dictionaries by key. The
function gives a
negative value if the
first dictionary is lesser
than the second
dictionary, a positive
value if the first
dictionary is greater
than the second
dictionary, and 0 if the
two dictionaries are
equal.

This function is used to


sort a dictionary in
Python. The function
takes two arguments:
the dictionary to be
sorted and the key on
which the sorting will
sorted()
be based. The key can
be a function, a list, or a
tuple. The function
returns a list of tuples,
with each tuple
consisting of the key
and the value.

It is a built-in function
len() that returns the length
of an object. It can be
used on various
objects such as strings,
lists, dictionaries, etc.

Python Dictionary keys() Method

The keys() method in Python dictionary returns a view object that displays all the
keys in the dictionary. View objects have some similar properties to the dictionary
they are defined in. For example, you can iterate through a view object to print all the
keys in the dictionary. It is possible to check if a key exists in a view object.

numbers = {1: 'one', 2: 'two', 3: 'three'}

# extracts the keys of the dictionary

dictionary keys = numbers.keys()

print(dictionaryKeys)

# Output: dict_keys([1, 2, 3])

Python Dictionary Values() Method

The values() method returns a view object that displays a list of all the values in the
dictionary.

You can get the list of all the values in the dictionary using the values() method. The
view object will reflect any changes made to the dictionary, so if you add or delete
values from the dictionary, the view object will also update. The values() method
differs from the keys() method because it doesn't take any arguments.

Check out the example on how to use the values() method in Python:

marks = {'Physics':67, 'Maths':87}

print(marks.values())

# Output: dict_values([67, 87])

Python program that sorts a dictionary by its values:

def sort_dict_by_values(input_dict):

# Sort the dictionary by values in ascending order

sorted_items = sorted(input_dict.items(), key=lambda x: x[1])

# Create a new dictionary from the sorted items

sorted_dict = {k: v for k, v in sorted_items}

return sorted_dict

# Test the function

my_dict = {'a': 3, 'b': 1, 'c': 2}

sorted_dict = sort_dict_by_values(my_dict)

# Print the sorted dictionary

print("Original Dictionary:", my_dict)

print("Sorted Dictionary:", sorted_dict)

output:

Original Dictionary: {'a': 3, 'b': 1, 'c': 2}

Sorted Dictionary: {'b': 1, 'c': 2, 'a': 3}

Python program that counts the number of occurrences of a letter in a string, using dictionaries.
def count_letters(string):
# Initialize an empty dictionary to store letter counts
letter_counts = {}
# Iterate over each character in the string
for char in string:
# Increment the count of the current character in the dictionary
if char in letter_counts:
letter_counts[char] += 1
else:
letter_counts[char] = 1
return letter_counts
# Test the function
input_string = input("Enter a string: ")
letter_counts = count_letters(input_string)
# Print the letter counts
for letter, count in letter_counts.items():
print(f"'{letter}' occurs {count} times.")

output:

Enter a string: my favourite language

'm' occurs 1 times.

'y' occurs 1 times.

' ' occurs 2 times.

'f' occurs 1 times.

'a' occurs 3 times.

'v' occurs 1 times.

'o' occurs 1 times.

'u' occurs 2 times.

'r' occurs 1 times.

'i' occurs 1 times.


't' occurs 1 times.

'e' occurs 2 times.

'l' occurs 1 times.

'n' occurs 1 times.

'g' occurs 2 times.

11. List some of useful string methods/functions? Give


a short note on indexing and slicing?
Write a Python script to check the given string is
Palindrome or not? Explain about string formatting
operator with example. Explain the use of join() and
split() string methods with examples. Describe why
strings are immutable with an example. How to convert a
string to a list in Python?

Python string is the collection of the characters surrounded by single quotes, double
quotes, or triple quotes. The computer does not understand the characters; internally,
it stores manipulated character as the combination of the 0's and 1's.

Each character is encoded in the ASCII or Unicode character. So we can say that Python
strings are also called the collection of Unicode characters.

In Python, strings can be created by enclosing the character or the sequence of


characters in the quotes. Python allows us to use single quotes, double quotes, or triple
quotes to create the string.

Consider the following example in Python to create a string.

Syntax:

1. str = "Hi Python !"

Here, if we check the type of the variable str using a Python script

1. print(type(str)), then it will print a string (str).


In Python, strings are treated as the sequence of characters, which means that Python
doesn't support the character data-type; instead, a single character written as 'p' is
treated as the string of length 1.

Creating String in Python


We can create a string by enclosing the characters in single-quotes or double- quotes.
Python also provides triple-quotes to represent the string, but it is generally used for
multiline string or docstrings.

1. #Using single quotes


2. str1 = 'Hello Python'
3. print(str1)
4. #Using double quotes
5. str2 = "Hello Python"
6. print(str2)
7.
8. #Using triple quotes
9. str3 = '''''Triple quotes are generally used for
10. represent the multiline or
11. docstring'''
12. print(str3)

Output:

Hello Python
Hello Python
Triple quotes are generally used for
represent the multiline or
docstring

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.
Consider the following example:

1. str = "HELLO"
2. print(str[0])
3. print(str[1])
4. print(str[2])
5. print(str[3])
6. print(str[4])
7. # It returns the IndexError because 6th index doesn't exist
8. print(str[6])

Output:

H
E
L
L
O
IndexError: string index out of range

As shown in Python, the slice operator [] is used to access the individual characters of
the string. However, we can use the : (colon) operator in Python to access the substring
from the given string. Consider the following example.
Here, we must notice that the upper range given in the slice operator is always
exclusive i.e., if str = 'HELLO' is given, then str[1:3] will always include str[1] = 'E', str[2]
= 'L' and nothing else.

Consider the following example:

1. # Given String
2. str = "JAVATPOINT"
3. # Start Oth index to end
4. print(str[0:])
5. # Starts 1th index to 4th index
6. print(str[1:5])
7. # Starts 2nd index to 3rd index
8. print(str[2:4])
9. # Starts 0th to 2nd index
10. print(str[:3])
11. #Starts 4th to 6th index
12. print(str[4:7])

Output:

JAVATPOINT
AVAT
VA
JAV
TPO

We can do the negative slicing in the string; it starts from the rightmost character,
which is indicated as -1. The second rightmost index indicates -2, and so on. Consider
the following image.

Consider the following example

1. str = 'JAVATPOINT'
2. print(str[-1])
3. print(str[-3])
4. print(str[-2:])
5. print(str[-4:-1])
6. print(str[-7:-2])
7. # Reversing the given string
8. print(str[::-1])
9. print(str[-12])

Output:
T
I
NT
OIN
ATPOI
TNIOPTAVAJ
IndexError: string index out of range

Reassigning Strings
Updating the content of the strings is as easy as assigning it to a new string. The string
object doesn't support item assignment i.e., A string can only be replaced with new
string since its content cannot be partially replaced. Strings are immutable in Python.

Consider the following example.

Example 1

1. str = "HELLO"
2. str[0] = "h"
3. print(str)

Output:

Traceback (most recent call last):


File "12.py", line 2, in <module>
str[0] = "h";
TypeError: 'str' object does not support item assignment

However, in example 1, the string str can be assigned completely to a new content as
specified in the following example.

Example 2

1. str = "HELLO"
2. print(str)
3. str = "hello"
4. print(str)

Output:

HELLO
hello

Deleting the String


As we know that strings are immutable. We cannot delete or remove the characters
from the string. But we can delete the entire string using the del keyword.

1. str = "JAVATPOINT"
2. del str[1]

Output:

TypeError: 'str' object doesn't support item deletion

Now we are deleting entire string.

1. str1 = "JAVATPOINT"
2. del str1
3. print(str1)

Output:

NameError: name 'str1' is not defined

String Operators

Operator Description

+ It is known as concatenation operator used to join the strings given either side
of the operator.

* It is known as repetition operator. It concatenates the multiple copies of the


same string.

[] It is known as slice operator. It is used to access the sub-strings of a particular


string.

[:] It is known as range slice operator. It is used to access the characters from the
specified range.

in It is known as membership operator. It returns if a particular sub-string is


present in the specified string.
not in It is also a membership operator and does the exact reverse of in. It returns
true if a particular substring is not present in the specified string.

r/R It is used to specify the raw string. Raw strings are used in the cases where we
need to print the actual meaning of escape characters such as "C://python".
To define any string as a raw string, the character r or R is followed by the
string.

% It is used to perform string formatting. It makes use of the format specifiers


used in C programming like %d or %f to map their values in python. We will
discuss how formatting is done in python.

Example
Consider the following example to understand the real use of Python operators.

1. str = "Hello"
2. str1 = " world"
3. print(str*3) # prints HelloHelloHello
4. print(str+str1)# prints Hello world
5. print(str[4]) # prints o
6. print(str[2:4]); # prints ll
7. print('w' in str) # prints false as w is not present in str
8. print('wo' not in str1) # prints false as wo is present in str1.
9. print(r'C://python37') # prints C://python37 as it is written
10. print("The string str : %s"%(str)) # prints The string str : Hello

Output:

HelloHelloHello
Hello world
o
ll
False
False
C://python37
The string str : Hello

Python String Formatting


Escape Sequence
Let's suppose we need to write the text as - They said, "Hello what's going on?"- the
given statement can be written in single quotes or double quotes but it will raise
the SyntaxError as it contains both single and double-quotes.

Example
Consider the following example to understand the real use of Python operators.

1. str = "They said, "Hello what's going on?""


2. print(str)

Output:

SyntaxError: invalid syntax

We can use the triple quotes to accomplish this problem but Python provides the
escape sequence.

The backslash(/) symbol denotes the escape sequence. The backslash can be followed
by a special character and it interpreted differently. The single quotes inside the string
must be escaped. We can apply the same as in the double quotes.

Example -

1. # using triple quotes


2. print('''''They said, "What's there?"''')
3.
4. # escaping single quotes
5. print('They said, "What\'s going on?"')
6.
7. # escaping double quotes
8. print("They said, \"What's going on?\"")

Output:

They said, "What's there?"


They said, "What's going on?"
They said, "What's going on?"

The list of an escape sequence is given below:


Sr. Escape Description
Sequence

1. \newline It ignores the print("Python1 \


Python2 \
new line. Python3")
Output:
Python1 Python2 Python3

2. \\ Backslash print("\\")
Output:
\

3. \' Single Quotes print('\'')


Output:
'

4. \\'' Double print("\"")


Quotes Output:
"

5. \a ASCII Bell print("\a")

6. \b ASCII print("Hello \b World")


Backspace(BS) Output:
Hello World

7. \f ASCII print("Hello \f World!")


Hello World!
Formfeed

8. \n ASCII print("Hello \n World!")


Linefeed Output:
Hello
World!

9. \r ASCII Carriege print("Hello \r World!")


Return(CR) Output:
World!

10. \t ASCII print("Hello \t World!")


Horizontal Output:
Tab Hello World!
11. \v ASCII Vertical print("Hello \v World!")
Tab Output:
Hello
World!

12. \ooo Character print("\110\145\154\154\157")


Output:
with octal Hello
value

13 \xHH Character print("\x48\x65\x6c\x6c\x6f")


with hex Output:
value. Hello

Here is the simple example of escape sequence.

1. print("C:\\Users\\DEVANSH SHARMA\\Python32\\Lib")
2. print("This is the \n multiline quotes")
3. print("This is \x48\x45\x58 representation")

Output:

C:\Users\DEVANSH SHARMA\Python32\Lib
This is the
multiline quotes
This is HEX representation

We can ignore the escape sequence from the given string by using the raw string. We
can do this by writing r or R in front of the string. Consider the following example.

1. print(r"C:\\Users\\DEVANSH SHARMA\\Python32")

Output:

C:\\Users\\DEVANSH SHARMA\\Python32

The format() method


The format() method is the most flexible and useful method in formatting strings. The
curly braces {} are used as the placeholder in the string and replaced by
the format() method argument. Let's have a look at the given an example:

1. # Using Curly braces


2. print("{} and {} both are the best friend".format("Devansh","Abhishek"))
3.
4. #Positional Argument
5. print("{1} and {0} best players ".format("Virat","Rohit"))
6.
7. #Keyword Argument
8. print("{a},{b},{c}".format(a = "James", b = "Peter", c = "Ricky"))

Output:

Devansh and Abhishek both are the best friend


Rohit and Virat best players
James,Peter,Ricky

Python String Formatting Using % Operator


Python allows us to use the format specifiers used in C's printf statement. The format
specifiers in Python are treated in the same way as they are treated in C. However,
Python provides an additional operator %, which is used as an interface between the

format specifiers and their values. In other words, we can say that it binds the format
specifiers to the values.

Consider the following example.

1. Integer = 10;
2. Float = 1.290
3. String = "Devansh"
4. print("Hi I am Integer ... My value is %d\nHi I am float ... My value is %f\nHi I am strin
g ... My value is %s"%(Integer,Float,String))

Output:

Hi I am Integer ... My value is 10


Hi I am float ... My value is 1.290000
Hi I am string ... My value is Devansh

Python String functions


Python provides various in-built functions that are used for string handling. Many
String functions
Method Description

capitalize() It capitalizes the first character of the


String. This function is deprecated in
python3

casefold() It returns a version of s suitable for case-


less comparisons.

center(width ,fillchar) It returns a space padded string with the


original string centred with equal
number of left and right spaces.

count(string,begin,end) It counts the number of occurrences of a


substring in a String between begin and
end index.

decode(encoding = 'UTF8', errors Decodes the string using codec


= 'strict') registered for encoding.

encode() Encode S using the codec registered for


encoding. Default encoding is 'utf-8'.

endswith(suffix It returns a Boolean value if the string


,begin=0,end=len(string)) terminates with given suffix between
begin and end.

expandtabs(tabsize = 8) It defines tabs in string to multiple


spaces. The default space value is 8.

find(substring ,beginIndex, It returns the index value of the string


endIndex) where substring is found between begin
index and end index.

format(value) It returns a formatted version of S, using


the passed value.

index(subsring, beginIndex, It throws an exception if string is not


endIndex) found. It works same as find() method.

isalnum() It returns true if the characters in the


string are alphanumeric i.e., alphabets or
numbers and there is at least 1 character.
Otherwise, it returns false.

isalpha() It returns true if all the characters are


alphabets and there is at least one
character, otherwise False.

isdecimal() It returns true if all the characters of the


string are decimals.

isdigit() It returns true if all the characters are


digits and there is at least one character,
otherwise False.

isidentifier() It returns true if the string is the valid


identifier.

islower() It returns true if the characters of a string


are in lower case, otherwise false.

isnumeric() It returns true if the string contains only


numeric characters.

isprintable() It returns true if all the characters of s are


printable or s is empty, false otherwise.

isupper() It returns false if characters of a string are


in Upper case, otherwise False.

isspace() It returns true if the characters of a string


are white-space, otherwise false.

istitle() It returns true if the string is titled


properly and false otherwise. A title
string is the one in which the first
character is upper-case whereas the
other characters are lower-case.
isupper() It returns true if all the characters of the
string(if exists) is true otherwise it returns
false.

join(seq) It merges the strings representation of


the given sequence.

len(string) It returns the length of a string.

ljust(width[,fillchar]) It returns the space padded strings with


the original string left justified to the
given width.

lower() It converts all the characters of a string to


Lower case.

lstrip() It removes all leading whitespaces of a


string and can also be used to remove
particular character from leading.

partition() It searches for the separator sep in S, and


returns the part before it, the separator
itself, and the part after it. If the separator
is not found, return S and two empty
strings.

maketrans() It returns a translation table to be used in


translate function.

replace(old,new[,count]) It replaces the old sequence of characters


with the new sequence. The max
characters are replaced if max is given.

rfind(str,beg=0,end=len(str)) It is similar to find but it traverses the


string in backward direction.

rindex(str,beg=0,end=len(str)) It is same as index but it traverses the


string in backward direction.
rjust(width,[,fillchar]) Returns a space padded string having
original string right justified to the
number of characters specified.

rstrip() It removes all trailing whitespace of a


string and can also be used to remove
particular character from trailing.

rsplit(sep=None, maxsplit = -1) It is same as split() but it processes the


string from the backward direction. It
returns the list of words in the string. If
Separator is not specified then the string
splits according to the white-space.

split(str,num=string.count(str)) Splits the string according to the


delimiter str. The string splits according
to the space if the delimiter is not
provided. It returns the list of substring
concatenated with the delimiter.

splitlines(num=string.count('\n')) It returns the list of strings at each line


with newline removed.

startswith(str,beg=0,end=len(str)) It returns a Boolean value if the string


starts with given str between begin and
end.

strip([chars]) It is used to perform lstrip() and rstrip()


on the string.

swapcase() It inverts case of all characters in a string.

title() It is used to convert the string into the


title-case i.e., The string meEruT will be
converted to Meerut.

translate(table,deletechars = '') It translates the string according to the


translation table passed in the function .
upper() It converts all the characters of a string to
Upper Case.

zfill(width) Returns original string leftpadded with


zeros to a total of width characters;
intended for numbers, zfill() retains any
sign given (less one zero).

We can convert a string to a list in Python by using the `list()` constructor or by using list
comprehension. Here's how you can do it:

1. Using the `list()` constructor:

my_string = "hello"

my_list = list(my_string)

print(my_list) # Output: ['h', 'e', 'l', 'l', 'o']

2. Using list comprehension:

my_string = "hello"

my_list = [char for char in my_string]

print(my_list) # Output: ['h', 'e', 'l', 'l', 'o']

Both methods will produce the same result, converting each character of the string into an individual
element in the list.

Program to check the given string is Palindrome or not:

def is_palindrome(string):

# Remove spaces and convert to lowercase

string = string.replace(" ", "").lower()

# Check if the string is equal to its reverse

return string == string[::-1]

# Test the function

input_string = input("Enter a string: ")

if is_palindrome(input_string):

print("The string is a palindrome.")

else:
print("The string is not a palindrome.")

output:

Enter a string: hello world

The string is not a palindrome.

Enter a string: huh

The string is a palindrome.

You might also like