Python Unit-3 Question Bank
Python Unit-3 Question Bank
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:
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
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)
my_list.extend([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'
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.
__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)
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:
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.
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.
• 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:
numbers = [1, 2, 3, 4, 5]
numbers[1] = 10
numbers.append(6)
numbers.remove(3)
length = len(numbers)
# Check if an element is in the list
if 4 in numbers:
print("List elements:")
print(num)
numbers.sort()
numbers.reverse()
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]
Here is an example Python program that will demonstrate the creation of tuples and some
common operations on tuples:
# my_tuple[0] = 10
length = len(my_tuple)
if 3.14 in my_tuple:
print(item)
# Concatenate tuples
tuple1 = (1, 2, 3)
# Repeat a tuple
repeated_tuple = tuple1 * 3
# Nested tuples
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.
# OR
my_set = {1, 2, 3, 4, 5}
my_set.add(2)
my_set.remove(3)
length = len(my_set)
print("Set elements:")
print(item)
set1 = {1, 2, 3}
set2 = {3, 4, 5}
my_list = [1, 2, 2, 3, 4, 4, 5]
unique_set = set(my_list)
• {key1: value1, key2: value2, key3: value3, ...}: These are the key-value pairs enclosed
in curly braces and separated by commas.
name = my_dict["name"]
age = my_dict["age"]
# country = my_dict["country"]
num_items = len(my_dict)
print("Dictionary elements:")
my_dict["age"] = 31
my_dict["country"] = "USA"
del my_dict["city"]
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
• 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.
• 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.
Understanding how each structure is represented syntactically can accelerate coding speed
and reduce errors.
• 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}
Allows
Yes Yes No Yes (Values)
Duplicates?
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.
For example:
num = [1, 2, 3, 4]
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 …).
Just note that when we slice lists, the start index is inclusive, but the end index is
exclusive.
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].
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].
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:
In a Python list, the element value can be changed by specifying the index number
and replacing it with a new value. For instance:
For adding new elements to a list in Python, you can use the ‘append ()’ method or
‘insert ()’ method.
The append() method adds the element to the end of the list. For example:
Fig: Adding element by using append () method
If you want to insert an element at a specific index, you should use the insert ()
method.
For instance:
Suppose you want to delete the item “get” from the list “mix”. We write it as
mix.remove(“get”).
You can check if the particular element exists in the list or not. The following
example can be used to perform the same:
You can check the number of items in the list by using ‘len ()’ method
Fig: To check the number of items in the 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:
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.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 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 :
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.
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.
• 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.
• 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.
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.
For all the data consumed and generated every day, algorithms should be good
enough to handle operations in large volumes of data.
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.
3. Worst Case: The complexity of solving problems for the worst input of
size n.
• Using Recursion: The List can be reversed by recursion without built-in functions.
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()
2. Copy()
3. Reverse()
The reverse method prints the items in a list in the reverse order.
Syntax: list.reverse()
4. Index()
The index method returns the index of the specified item in a list.
Syntax: list.index(element)
• 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.
• 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')
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:
def print_pattern(rows):
# Print asterisks
for k in range(i):
print("*", end="")
print()
rows = 4
print_pattern(rows)
output:
****
***
**
• 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:
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'}
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
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'})
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})
Set List
Sets don’t allow to change or replace the elements. Changing parts is possible in Python lists.
2. Set vs Tuple:
Set Tuple
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
Sets are represented in curly brackets. Dictionaries are enclosed in curly brackets
in the form of key-value pairs.
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
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:
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
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`.
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
# Dictionary Comprehension
print(squares)
Function Description
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.
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.
print(dictionaryKeys)
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:
print(marks.values())
def sort_dict_by_values(input_dict):
return sorted_dict
sorted_dict = sort_dict_by_values(my_dict)
output:
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:
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.
Syntax:
Here, if we check the type of the variable str using a Python script
Output:
Hello Python
Hello Python
Triple quotes are generally used for
represent the multiline or
docstring
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.
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.
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.
Example 1
1. str = "HELLO"
2. str[0] = "h"
3. print(str)
Output:
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
1. str = "JAVATPOINT"
2. del str[1]
Output:
1. str1 = "JAVATPOINT"
2. del str1
3. print(str1)
Output:
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 range slice operator. It is used to access the characters from the
specified range.
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.
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
Example
Consider the following example to understand the real use of Python operators.
Output:
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 -
Output:
2. \\ Backslash print("\\")
Output:
\
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
Output:
format specifiers and their values. In other words, we can say that it binds the format
specifiers to the values.
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:
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:
my_string = "hello"
my_list = list(my_string)
my_string = "hello"
Both methods will produce the same result, converting each character of the string into an individual
element in the list.
def is_palindrome(string):
if is_palindrome(input_string):
else:
print("The string is not a palindrome.")
output: