Python Set

Python Set Tutorial

Introduction:

In Python, a set is an unordered collection of unique elements. Sets are mutable and can be modified using various methods. They can be used to perform mathematical set operations like union, intersection, and difference. This tutorial will walk you through the basics of sets in Python.

Creating Sets:

To create a set in Python, you can use curly braces `{}` or the built-in `set()` function. Here’s an example.

				
					# Using curly braces
my_set = {1, 2, 3, 4, 5}

# Using set() function
my_set = set([1, 2, 3, 4, 5])

				
			

Features of Python Set:

  1. Uniqueness: Sets are collections of unique elements. Each element appears only once in a set. If you try to add a duplicate element, it will be ignored.
  2. Mutable: Sets are mutable, meaning you can modify them by adding or removing elements after they are created.
  3. Unordered: Sets are unordered collections, which means the elements are not stored in any particular order. You cannot access elements by indexing or slicing.
  4. Creation: Sets can be created using curly braces `{}` or the built-in `set()` function. For example.
				
					my_set = {1, 2, 3}  # Using curly braces
my_set = set([1, 2, 3])  # Using set() function

				
			
  1. Adding and Removing Elements: Elements can be added to a set using the `add()` method, and multiple elements can be added using the `update()` method. Elements can be removed using the `remove()` or `discard()` method.
				
					my_set.add(4)  # Adds element 4 to the set
my_set.update([5])  # Adds elements 5 
my_set.remove(1)  # Removes element 1

				
			
  1. Set Operations: Sets support various mathematical operations such as union, intersection, and difference. These operations can be performed using methods or operators.
				
					set1 = {1, 2, 3}
set2 = {3, 4, 5}

union_set = set1.union(set2)  # Union of set1 and set2
intersection_set = set1.intersection(set2)  # Intersection of set1 and set2
difference_set = set1 - set2  # Difference between set1 and set2

				
			
  1. Membership Testing: Sets provide an efficient way to test if an element exists in a set using the `in` operator. This operation has a constant-time complexity compared to lists or tuples.
				
					my_set = {1, 2, 3}
print(1 in my_set)  # Output: True
print(5 in my_set)  # Output: False

				
			
  1. Iteration: You can iterate over the elements of a set using a `for` loop, which will visit each element in an arbitrary order.
				
					my_set = {1, 2, 3}
for element in my_set:
    print(element)

				
			

Advantages of Python Set:

  1. Unique Elements: Sets are designed to store only unique elements. If you have a collection of items where duplicates are not needed, sets can automatically handle the uniqueness for you. This feature eliminates the need for additional logic to check for duplicates.
  2. Fast Membership Testing: Sets provide a highly efficient way to check whether an element is present in the set or not. The membership testing operation using the `in` operator has a constant-time complexity, regardless of the size of the set. This makes sets a great choice when you need to quickly determine whether an element exists in a collection.
  3. Mathematical Set Operations: Sets in Python support a wide range of mathematical set operations such as union, intersection, difference, and symmetric difference. These operations can be performed using methods or operators, allowing you to manipulate sets and extract meaningful information easily.
  4. Performance: Sets are implemented internally using hash tables, which results in fast access and retrieval of elements. Hash tables provide constant-time average case complexity for adding, removing, and retrieving elements. This makes sets efficient when working with large datasets or performing operations on multiple sets.
  5. Set Operations: Sets offer convenient methods to perform common set operations, making your code more expressive and concise. For example, you can check if one set is a subset or superset of another, find the intersection of multiple sets, or check for disjoint sets.
  6. Mutable: Unlike frozensets, sets in Python are mutable. You can add or remove elements from a set after it is created. This flexibility allows you to modify sets based on your requirements.
  7. Iteration: Sets can be iterated efficiently using a `for` loop, allowing you to process each element in the set easily. The iteration order of elements in a set is arbitrary, but consistent within the same run of a program.
  8. Efficient Duplicate Removal: If you have a collection with duplicates, converting it to a set and then back to a list can quickly remove the duplicates. This is a simple and efficient way to ensure uniqueness in a list of elements.

Disadvantages of Python Set:

  1. Unordered Collection: Sets are unordered collections, which means the order of elements is not preserved. If you need to maintain the order of elements or access them by index, sets may not be suitable for your specific use case. In such situations, you might consider using lists or other data structures.
  2. Unique Elements Only: Sets are designed to store only unique elements. If you have a need to store duplicate elements or require multiple occurrences of an item, sets may not be the appropriate choice. In such cases, you would need to use other data structures like lists or dictionaries.
  3. Non-Hashable Elements: Elements in a set must be hashable, which means they need to have a hash value that remains constant throughout their lifetime. This requirement limits the types of objects that can be stored in a set. Mutable objects like lists or dictionaries cannot be stored directly in a set, but you can use their immutable counterparts (e.g., tuples) instead.
  4. Set Operations vs. List Operations: While sets provide convenient operations for set-specific tasks like union, intersection, and difference, they may not provide the same level of functionality for common list operations. For example, sets do not provide direct support for indexing, slicing, or sorting. If you require these operations frequently, using lists or other data structures might be more appropriate.
  5. Memory Overhead: Sets consume more memory compared to lists or tuples due to the internal data structures used for efficient element lookup. If memory efficiency is a concern, especially for large collections, using sets may not be the most optimal choice.
  6. Iteration Order: While iteration over a set is possible, the order in which elements are iterated is arbitrary and not based on the order in which they were added. If you require a specific order or need to maintain the order of elements, sets may not meet your requirements.
  7. No Key-Value Association: Sets only store individual elements and do not provide a key-value association like dictionaries. If you need to associate values with specific elements, dictionaries would be a more suitable choice.

Deleting Python set:

In Python, you can delete a set using the `del` keyword. Here’s an example of how to delete a set. Here’s an example:

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

# Deleting the set
del my_set

# Trying to access the set after deletion will raise an error
print(my_set)  # Raises NameError: name 'my_set' is not defined

				
			

In the example above, the `del` keyword is used to delete the `my_set` variable, which contains the set. After deleting the set, any attempt to access or use the set will result in a `NameError` because the set no longer exists.

Indexing in Python Set:

In Python, sets are unordered collections, and therefore, they do not support indexing. Since sets do not maintain any particular order of elements, there is no way to access elements by their indices. Here’s an example:

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

# Trying to access an element by index will result in a TypeError
print(my_set[0])  # Raises TypeError: 'set' object is not subscriptable

				
			

As seen in the example, attempting to access an element in a set using indexing, such as `my_set[0]`, will raise a `TypeError`. This is because sets are not subscriptable like lists or tuples, where you can access elements using their indices.

Slicing in Python Set:

In Python, tuples are ordered collections of elements, and you can use slicing to extract a portion of a tuple. Slicing allows you to create a new tuple containing a specified range of elements from the original tuple. Here’s an example:

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

# Slicing to extract a portion of the tuple
subset = my_tuple[1:5]

print(subset)  # Output: (2, 3, 4, 5)

				
			

In the example above, the slicing operation `my_tuple[1:5]` creates a new tuple `subset ` that contains elements from index 1 up to (but not including) index 5 of the original tuple `my_tuple`. The resulting subset tuple is `(2, 3, 4, 5)`.

The slicing syntax `start:stop:step` allows you to control the range of elements to include in the new tuple. Here are a few examples:

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

subset = my_tuple[1:5]  # Slicing from index 1 to 5 (exclusive)
print(subset)  # Output: (2, 3, 4, 5)

subset = my_tuple[:3]  # Slicing from the start up to index 3 (exclusive)
print(subset)  # Output: (1, 2, 3)

subset = my_tuple[2:]  # Slicing from index 2 to the end
print(subset)  # Output: (3, 4, 5, 6)

subset = my_tuple[::2]  # Slicing with a step of 2
print(subset)  # Output: (1, 3, 5)

				
			

Python Set operators:

  1. Union: The union of two sets `A` and `B` contains all unique elements from both sets. In Python, you can perform the union operation using the `union()` method or the `|` operator.
				
					set1 = {1, 2, 3}
set2 = {3, 4, 5}

union = set1.union(set2)  # Using method
union = set1 | set2  # Using operator
print(union)  # Output: {1, 2, 3, 4, 5}

				
			
  1. Intersection: The intersection of two sets `A` and `B` contains only the elements that are common to both sets. In Python, you can perform the intersection operation using the `intersection()` method or the `&` operator.
				
					set1 = {1, 2, 3}
set2 = {3, 4, 5}

intersection = set1.intersection(set2)  # Using method
intersection = set1 & set2  # Using operator
print(intersection)  # Output: {3}

				
			
  1. Difference: The difference between two sets `A` and `B` contains the elements that are in `A` but not in `B`. In Python, you can perform the difference operation using the `difference()` method or the `-` operator.
				
					set1 = {1, 2, 3}
set2 = {3, 4, 5}

difference = set1.difference(set2)  # Using method
difference = set1 - set2  # Using operator
print(difference)  # Output: {1, 2}

				
			
  1. Symmetric Difference: The symmetric difference of two sets `A` and `B` contains the elements that are in either `A` or `B`, but not both. In Python, you can perform the symmetric difference operation using the `symmetric_difference()` method or the `^` operator.
				
					set1 = {1, 2, 3}
set2 = {3, 4, 5}

symmetric_difference = set1.symmetric_difference(set2)  # Using method
symmetric_difference = set1 ^ set2  # Using operator
print(symmetric_difference)  # Output: {1, 2, 4, 5}

				
			

Python Set functions:

  1. len(): The `len()` function returns the number of elements in a set.
				
					my_set = {1, 2, 3, 4, 5, 6}
length = len(my_set)
print(length)  # Output: 6

				
			
  1. add(): The `add()` function adds an element to a set.
				
					my_set = {1, 2, 3, 4}
my_set.add(5)
print(my_set)  # Output: {1, 2, 3, 4, 5}

				
			
  1. remove(): The `remove()` function removes an element from a set. It raises a KeyError if the element does not exist in the set.
				
					my_set = {1, 2, 3, 4}
my_set.remove(3)
print(my_set)  # Output: {1, 2, 4}

				
			
  1. discard(): The `discard()` function removes an element from a set if it exists. It does not raise an error if the element is not found.
				
					my_set = {1, 2, 3, 4}
my_set.discard(4)
print(my_set)  # Output: {1, 2, 3}

				
			
  1. pop(): The `pop()` function removes and returns an arbitrary element from the set. Since sets are unordered, the popped element is not guaranteed to be the first or last element.
				
					my_set = {1, 2, 3, 4}
element = my_set.pop()
print(element)  # Output: a random element, e.g., 1

				
			
  1. clear(): The `clear()` function removes all elements from a set, making it empty.
				
					my_set = {1, 2, 3, 4}
my_set.clear()
print(my_set)  # Output: set()

				
			
  1. copy(): The `copy()` function creates a shallow copy of a set, allowing you to work with a separate copy of the original set.
				
					my_set = {1, 2, 3}
my_set_new = my_set.copy()
print(my_set_new)  # Output: {1, 2, 3}

				
			

Python Tuple

Python Tuple Tutorial

Introduction:

Python tuples are a data structure used to store an ordered collection of elements. Unlike lists, tuples are immutable, meaning their values cannot be changed once created. This can be useful in situations where you want to ensure that data is not accidentally modified. Tuples are also hash able, which means they can be used as keys in dictionaries.

Creating a Tuple:

Tuples can be created using parentheses, with elements separated by commas (,) and also bu using tuple() keyword. Here’s an example.

				
					tup = (1,2,3,4)
print(tup) # Output : (1,2,3,4)

tup = tuple(1,2,3,4)
print(tup) # Output : (1,2,3,4)

				
			

Features of python tuple:

A tuple is an immutable sequence in Python that can contain elements of different data types. Here are the key features of a Python tuple:

  • 1). Immutable: Once created, a tuple cannot be modified. You cannot add, remove, or modify elements in a tuple. This immutability ensures data integrity and allows tuples to be used as keys in dictionaries.
  • 2). Ordered : Elements in a tuple are ordered and maintain their positions. The order of elements in a tuple is preserved, and you can access them using their indices.
  • 3). Heterogeneous Data Types : A tuple can store elements of different data types. For example, you can have a tuple containing an integer, a string, and a float.
  • 4). Indexing and Slicing : You can access individual elements of a tuple using their indices. Tuples support both positive and negative indexing, where negative indices count from the end of the tuple. Slicing allows you to extract a portion of the tuple by specifying a range of indices.
  • 5). Iteration : Tuples can be iterated over using loops. This allows you to access each element in the tuple sequentially.
  • 6). Hashability : Tuples are hashable, which means they can be used as keys in dictionaries and elements in sets. This property is due to their immutability.
  • 7). Nesting : Tuples can be nested inside other tuples. This allows you to create complex data structures using tuples.
  • 8). Size Efficiency : Tuples are more memory-efficient compared to lists because they are immutable. This makes tuples a suitable choice when you have a fixed collection of elements that won’t change.
  • 9). Function Arguments and Return Values : Tuples are often used to pack multiple values together and pass them as arguments to functions or return multiple values from a function.
  • 10). Tuple Packing and Unpacking: You can pack multiple values into a tuple using a comma-separated list of values. Similarly, you can unpack a tuple by assigning its elements to individual variables.

Advantages of python tuple:

  1. Immutability:

Tuples in Python are immutable, meaning once created, their elements cannot be modified. This immutability provides several advantages. Firstly, it ensures data integrity by preventing accidental modification of elements. This is particularly useful in scenarios where data should remain constant, such as configuration settings or constant lookup tables. Secondly, immutability allows tuples to be used as keys in dictionaries, as they provide a stable and unchangeable identity. This makes tuples a suitable choice for scenarios where immutability is desired.

  1. Performance Efficiency:

Tuples are more memory-efficient than lists in Python. Since tuples are immutable, they are stored more compactly in memory compared to lists, which can dynamically resize as elements are added or removed. This efficiency can be beneficial when dealing with large collections of data or in scenarios where memory optimization is crucial. Additionally, accessing elements in tuples is generally faster than accessing elements in lists since tuples have a simpler internal structure.

  1. Tuple Packing and Unpacking:

Python tuples support a convenient feature called tuple packing and unpacking. Tuple packing allows you to create tuples by grouping multiple values together. Unpacking, on the other hand, allows you to assign elements of a tuple to individual variables. This feature makes tuples useful in scenarios where you need to return multiple values from a function or swap variable values efficiently. It provides a concise and intuitive way to work with multiple elements simultaneously.

  1. Sequence Operations:

Tuples support sequence operations such as indexing and slicing, similar to lists and strings. This allows you to access specific elements or extract subsets of elements from a tuple efficiently. Additionally, tuples support iteration using loops, making them iterable data structures. This flexibility in sequence operations makes tuples suitable for various use cases, such as iterating over collections, accessing elements by index, or performing operations on specific subsets of data.

  1. Hashability and Uniqueness:

Tuples in Python are hashable, meaning they can be used as keys in dictionaries or elements in sets. This is because tuples are immutable and their hash value remains constant. This property enables efficient lookup and retrieval of data when using tuples as keys or elements. Additionally, tuples can preserve uniqueness, allowing you to store unique combinations of elements in a collection.

Disadvantages of python tuple:

  1. Immutability:

One of the primary disadvantages of tuples is their immutability. Once a tuple is created, its elements cannot be modified. While immutability provides data integrity and stability, it can be restrictive in scenarios where dynamic changes to data are required. If you need to add, remove, or modify elements frequently, a tuple might not be the most suitable data structure. In such cases, mutable data structures like lists might be more appropriate.

  1. Limited Mutability:

While tuples are immutable as a whole, they can contain mutable objects as elements. This means that if a tuple contains mutable objects like lists or dictionaries, those objects can be modified even though the tuple itself cannot be changed. However, care must be taken when modifying mutable objects within a tuple to avoid unexpected behavior or inadvertent modifications.

  1. Lack of Flexibility:

Compared to lists, tuples have limited flexibility. Tuples do not provide built-in methods for adding or removing elements, sorting, or reversing. These operations require converting the tuple to a list, performing the operation, and then converting it back to a tuple. This extra step can be cumbersome and less efficient compared to directly manipulating lists. If you anticipate frequent modifications or dynamic operations on your data, using lists might offer more flexibility.

  1. Inefficient for Large-Scale Modifications:

Due to their immutability, modifying a tuple requires creating a new tuple with the desired modifications. This process can be inefficient and memory-consuming when dealing with large-scale modifications. In such cases, mutable data structures like lists, where elements can be modified in-place, can provide better performance.

  1. Limited Data Analysis Capabilities:

Tuples are not well-suited for complex data analysis tasks or mathematical operations. While they can store numeric values, tuples lack built-in mathematical functions and libraries commonly used for advanced calculations or statistical operations. If your application requires extensive data analysis, other data structures like NumPy arrays or pandas DataFrames might be more suitable.

Deleting python tuple:

In Python, tuples are immutable data structures that allow you to store a collection of elements. Once created, a tuple cannot be modified. However, there may be scenarios where you need to delete a tuple or remove it from memory. In this article, we will explore different techniques to effectively delete a tuple in Python, considering the immutability of tuples.

Tuple Immutability:

Tuples in Python are immutable, meaning their elements cannot be modified or removed individually. This property ensures data integrity and enables tuples to be used as keys in dictionaries. However, it also implies that we cannot directly delete or modify elements within a tuple. Instead, we need to adopt alternative approaches to achieve the desired outcome.

Method 1: Using the “del” keyword:

One way to delete a tuple is by using the `del` keyword. While it cannot delete individual elements within a tuple, it can remove the entire tuple object from memory. Here’s an example:

				
					my_tup = (1, 2, 3, 4)
del my_tup

				
			

In this method, the `del` keyword is used to delete the reference to the tuple.

Method 2: Reassigning the tuple variable:

Another approach to “delete” a tuple is by reassigning the variable that references it. By assigning a new value to the variable, the old tuple becomes unreachable and eligible for garbage collection. Here’s an example:

				
					my_tup = (1, 2, 3, 4)
my_tup = ()

				
			

In this method, an empty tuple is assigned to the variable `my_tup`, effectively replacing the original tuple.

Indexing in python tuple:

In Python, tuples are immutable sequences that allow you to store a collection of elements. Indexing is a fundamental operation that enables you to access individual elements within a tuple.

Understanding Tuple Indexing:

Tuples in Python are ordered collections, meaning the elements maintain a specific order. Each element in a tuple is assigned an index, starting from 0 for the first element. Indexing allows you to retrieve individual elements based on their position within the tuple.

Accessing Elements using Positive Indexing:

Positive indexing is the most common way to access elements in a tuple. It involves using the index value starting from 0 and incrementing by one for each subsequent element.  Here’s an example:

				
					my_tup = (1, 2, 3, 4)
print(my_tuple[0])  # Accessing the first element i.e. 1
print(my_tuple[2])  # Accessing the third element i.e. 3

				
			

In this case, my_tup[0] retrieves the first element 1, and my_tup[2] retrieves the third element 2 from the tuple.

Accessing Elements using Negative Indexing:

Python also supports negative indexing, where the index counts from the end of the tuple. The last element has an index of -1, the second-to-last element has an index of -2, and so on. Negative indexing provides a convenient way to access elements from the end of the tuple. Here’s an example:

				
					my_tup = (1, 2, 3, 4)
print(my_tuple[-1])  # Accessing the last element i.e. 4
print(my_tuple[-2])  # Accessing the second last element i.e. 3

				
			

In this example, `my_tup[-1]` retrieves the last element 4, and `my_tup[-2]` retrieves the second last element 3 from the tuple.

Slicing in Python Tuples:

Understanding Tuple Slicing:

Slicing is a way to extract a portion of a sequence by specifying a range of indices. It is particularly useful when you want to work with a subset of elements within a tuple. The syntax for slicing is `start:stop:step`, where `start` is the starting index, `stop` is the ending index (exclusive), and `step` is the increment value.

Basic Slicing:

To perform a basic slice, you only need to provide the `start` and `stop` indices. This will extract the elements from the starting index up to, but not including, the ending index. Here’s an example:

				
					tup = (1, 2, 3, 4, 5)
print(tup[1:4])  # Extracting elements from index 1 to 3

				
			

In this case, the slice `tup[1:4]` retrieves elements with indices 1, 2, and 3, resulting in the tuple (2, 3, 4).

Step Value in Slicing:

You can also specify a step value to skip elements during the slice. The step value determines the increment between successive elements. Here’s an example:

				
					tup = (1, 2, 3, 4, 5)
print(tup[::3])  # Extracting every third element

				
			

In this example, the slice `tup[::3]` extracts elements with a step size of 3, resulting in the tuple (1, 5).

Negative Indices in Slicing:

Python allows the use of negative indices in slicing. Negative indices count from the end of the tuple. This can be useful when you want to extract elements from the end. Here’s an example:

				
					tup = (1, 2, 3, 4, 5)
print(tup[-4:-1])  # Extracting elements from index -4 to -2

				
			

In this case, the slice `tup [-3:-1]` retrieves elements with indices -4 and -2, resulting in the tuple (2, 3, 4).

Combining Slicing Techniques:

You can combine different slicing techniques to create more complex slices. Here’s an example:

				
					tup = (1, 2, 3, 4, 5)
print(tup[0:5:2])  # Extracting elements from index 0 to 4 with a step size of 2

				
			

In this example, the slice `tup [0:5:2]` extracts elements with indices 0, 2 and 4 resulting in the tuple (1, 3, 5).

Python tuple operators:

  1. Concatenation Operator (+):

The concatenation operator (+) allows you to combine two tuples to create a new tuple. It produces a new tuple that includes all the elements from both tuples, maintaining their order. Here’s an example:

				
					tup1 = (1, 2, 3)
tup2 = (4, 5, 6)
concatenated_tuples = tup1 + tup2

				
			

In this case, the `concatenated_tuples` will be (1, 2, 3, 4, 5, 6), resulting from the concatenation of `tup1` and `tup2`.

  1. Repetition Operator (*):

The repetition operator (*) allows you to create a new tuple by repeating the elements of an existing tuple a specified number of times. It produces a new tuple that contains the repeated elements. Here’s an example:

				
					tup = (1, 2, 3)
repeated_tup = tup * 2

				
			

In this example, the `repeated_tup` will be (1, 2, 3, 4, 1, 2, 3, 4), as the elements of `tup ` are repeated two times.

  1. Comparison Operators (==, !=, <, >, <=, >=):

You can use comparison operators to compare tuples based on their elements. The comparison is performed element-wise, starting from the first element. Here’s an example:

				
					tup1 = (1, 2, 3, 4)
tup2 = (5, 6, 7, 8)
print(tuple1 < tuple2)  # Output: True

				
			

In this case, the `<` operator compares the first element of `tup1` with the first element of `tup2` and returns True because 1 is less than 4.

  1. Membership Operators (in, not in):

Membership operators allow you to check if an element is present in a tuple or not. The `in` operator returns True if the element exists in the tuple, while the `not in` operator returns True if the element does not exist. Here’s an example:

				
					tup = (1, 2, 3)
print(1 in tup)      # Output: True
print(5 not in tup)  # Output: True

				
			

In this example, the first statement returns True as 1 is present in `tup `, while the second statement returns True as 5 is not present.

Python tuple functions:

  1. len():

The `len()` function allows you to determine the length or size of a tuple. It returns the number of elements present in the tuple. Here’s an example:

				
					tup = (1, 2, 3, 4)
tuple_length = len(tup)
print(tuple_length)  # Output: 4

				
			

In this case, `len(tup)` returns 4, as `tup ` contains four elements.

  1. min() and max():

The `min()` and `max()` functions allow you to find the minimum and maximum values, respectively, within a tuple. Here’s an example:

				
					tup = (1, 2, 3, 4, 5, 6)
minimum_value = min(tup)
maximum_value = max(tup)
print(minimum_value)  # Output: 1
print(maximum_value)  # Output: 6

				
			

In this example, `min(tup)` returns the minimum value of 1, while `max(tup)` returns the maximum value of 6.

  1. sum():

The `sum()` function allows you to calculate the sum of all the elements within a tuple. It works for tuples that contain elements that are numeric. Here’s an example:

				
					tup = (1, 2, 3, 4)
total = sum(tup)
print(total)  # Output: 10

				
			

In this case, `sum(tup)` returns 10, which is the sum of all the elements in `tup `.

  1. sorted():

The `sorted()` function returns a new sorted list containing all the elements from a tuple. Here’s an example:

				
					tup = (5, 2, 4, 3, 1)
sorted_list = sorted(tup)
print(sorted_list)  # Output: `[1, 2, 3, 4, 5]

				
			

In this example, `sorted(tup)` returns a sorted list `[1, 2, 3, 4, 5]` while leaving the original tuple unchanged.

  1. count():

The `count()` function allows you to count the occurrences of a specific element within a tuple. It returns the number of times the element appears. Here’s an example:

				
					tup = (1, 1, 2, 3, 2, 4, 1)
element_count = tup.count(1)
print(element_count)  # Output: 3

				
			

In this case, `tup.count(1)` returns 3, as the value 1 appears three times within `tup `.

Python List

Python List Tutorial

Introduction:

Lists are one of the most commonly used data structures in Python. A list is a collection of elements, which can be of any type, including numbers, strings, and other lists etc. Lists are mutable, which means you can make changes in the list by adding, removing, or changing elements.

List declaration:

To declare a list in Python, you can use square brackets [] and separate the elements with commas. Here’s an example:

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

In the above example, we created a list called new_list that contains five integers.

You can also create an empty list by using the list() function or just an empty set of square brackets [].  Here are some examples:

list_1 = list()
list_2 = []

Both of the examples above create an empty list called empty_list_1 and list_2.

You can also create a list of a specific size filled with a default value using the * operator.  Here’s an example:

empty_list_1 = []
empty_list_2 = list()

In the example above, we created a list called my_list that contains three 1 values.

my_list = [1, 1, 1]

List Rules:

  1. List elements can be of different data types, including integers, floats, strings, booleans, and other objects.
  2. Lists are mutable, which means that we can modify it by adding, removing, or changing elements.
  3. Index of elements in the list starts from 0. We can access individual elements of a list by their index.
  4. We can use slicing to extract a subset of elements from a list. Slicing returns a new list that includes the specified range of elements.
  5. Lists can be concatenated using the ‘+’ operator.
  6. Lists can be nested, meaning that you can have a list of lists.
  7. Lists can be sorted in ascending or descending order using the sorted() function or the sort() method.
  8. We can use the len() function to get the number of elements in a list.
  9. We can iterate over the elements of a list using a for loop or list comprehension.
  10. Two lists can be compared for equality using the ‘==’ operator. Two lists are considered equal if they have the same elements in the same order.

Python list features:

  1. Mutable: Lists are mutable, meaning you can modify their elements by assigning new values to specific indices.
  2. Ordered: Lists maintain the order of elements as they are added. The first element added will be at index 0, the second element at index 1, and so on.
  3. Dynamic Size: Python lists can dynamically grow or shrink in size as elements are added or removed. You don’t need to specify the size beforehand.
  4. Heterogeneous Elements: Lists can contain elements of different data types. For example, a single list can store integers, floats, strings, or even other lists.
  5. Indexing and Slicing: You can access individual elements in a list using square brackets notation and their index. Additionally, you can slice lists to extract a portion of elements by specifying start and end indices.
  6. Iteration: Lists can be easily iterated over using loops or list comprehensions, allowing you to process each element or perform operations on the entire list.
  7. Built-in Functions: Python provides a range of built-in functions specifically designed for working with lists. These include functions like `len()`, `max()`, `min()`, `sum()`, `sorted()`, and more.
  8. Versatile Data Structure: Lists are a versatile data structure used in a variety of scenarios. They are commonly used for storing collections of related items, implementing stacks, queues, and other data structures, and for general-purpose data manipulation.
  9. List Comprehensions: Python allows you to create new lists by performing operations on existing lists using concise and expressive syntax called list comprehensions. This feature provides an efficient and readable way to manipulate lists.
  10. Extensive Methods: Python lists come with a range of built-in methods that enable various operations like adding or removing elements, sorting, reversing, searching, and more. These methods make it easy to work with lists and perform common list operations efficiently.

Python list advantages:

  1. Flexibility: Python lists are highly flexible and versatile. They can store elements of different data types, allowing you to create lists with a mix of integers, floats, strings, and other objects. This flexibility makes lists suitable for a wide range of applications.
  2. Dynamic Size: Lists in Python can grow or shrink dynamically as elements are added or removed. Unlike some other programming languages, you don’t need to specify the size of a list beforehand. This dynamic resizing capability makes it convenient to work with collections of varying lengths.
  3. Easy Element Manipulation: Python provides intuitive ways to manipulate list elements. You can easily access, modify, or delete elements based on their indices. This makes it convenient to update or rearrange elements within a list as needed.
  4. Iteration and Looping: Python lists can be easily iterated over using loops or list comprehensions. This allows you to process each element in a list sequentially or apply operations to the entire list, making it straightforward to perform calculations or transformations on list data.
  5. Built-in Functions and Methods: Python provides a rich set of built-in functions and methods specifically designed for working with lists. These functions and methods simplify common list operations such as sorting, searching, filtering, adding or removing elements, and more. This extensive set of tools saves you time and effort when working with lists.
  6. Powerful List Comprehensions: Python offers list comprehensions, which are concise and expressive ways to create new lists based on existing ones. List comprehensions allow you to apply transformations, conditions, and calculations to existing lists in a single line of code, making your code more readable and compact.
  7. Compatibility with Other Data Structures: Lists in Python can easily be converted to and from other data structures like tuples or arrays. This compatibility allows you to take advantage of the specific features and benefits offered by different data structures as needed.
  8. Common Data Structure: Python lists are widely used and well-supported. They are a fundamental data structure in Python, and you’ll find them extensively used in libraries, frameworks, and code examples. This popularity means that there is a wealth of resources, documentation, and community support available for working with lists.

Python list disadvantages:

  1. Slow for Large Data Sets: Python lists may become inefficient when dealing with large data sets or performing operations that require frequent insertions or deletions. As lists are dynamically resized, these operations can be time-consuming, particularly if the list needs to be resized multiple times.
  2. Sequential Search: When searching for an element in a list, Python performs a sequential search, iterating through each element until a match is found. This linear search approach can be slow for large lists, especially when compared to more efficient search algorithms like binary search available for sorted arrays.
  3. Fixed Overhead: Each element in a Python list requires additional memory to store its value and associated metadata, such as the data type and object reference. This fixed overhead per element can be significant when dealing with large lists, potentially consuming more memory than other data structures optimized for memory efficiency.
  4. Lack of Constant-Time Operations: Certain operations on Python lists, such as inserting or removing an element at a specific index, can be slow for large lists. These operations may require shifting or reassigning elements, resulting in a time complexity of O(n), where n is the number of elements in the list. In contrast, other data structures like arrays or linked lists can provide constant-time operations for these operations.
  5. Limited Sorting Options: Python’s built-in sorting method, `list.sort()`, uses a variant of the quicksort algorithm. While it is efficient in most cases, it may not be suitable for certain specialized sorting requirements. For such scenarios, you may need to implement custom sorting algorithms or explore external libraries for specific sorting needs.
  6. Not Suitable for Unique Elements: Python lists can contain duplicate elements. If you require a collection that only allows unique elements, you need to perform additional checks or use alternative data structures like sets or dictionaries.
  7. Mutable Nature: While mutability can be an advantage, it can also lead to unintended changes in list elements. If a list is shared among multiple parts of a program or passed as a parameter to functions, modifying the list can affect other parts of the code unintentionally. This can lead to potential bugs or unexpected behavior.

Python List Indexing and Slicing

In Python first element in the list has an index of 0. You can access elements in a list by their index using square brackets. Here’s an example:

# Define a list
my_list = ['apple', 'banana', 'cherry']

# Access the first element
first_element = my_list[0] # 'apple'

# Access the second element
second_element = my_list[1] # 'banana'

# Access the third element
third_element = my_list[2] # 'cherry'

# Print the elements
print("First element:", first_element)
print("Second element:", second_element)
print("Third element:", third_element)

You can also use negative indexing to access the list elements in the reverse order. Here’s an example:

# Define a list
my_list = ['apple', 'banana', 'cherry']

# Access the last element
last_element = my_list[-1] # 'cherry'

# Access the second-to-last element
second_last_element = my_list[-2] # 'banana'

# Access the third-to-last (or first) element
third_last_element = my_list[-3] # 'apple'

# Print the elements

print("Last element:", last_element)
print("Second-to-last element:", second_last_element)
print("Third-to-last element:", third_last_element)
Slicing rules to created sublist in python:

Here are the rules for slicing in Python:

  1. Slicing uses the colon : operator to specify a range of indices. The syntax is my_list[start_index:end_index:step].
  2. The start_index is the index of the first element to include in the slice. If not specified, it defaults to 0.
  3. The end_index is the index of the first element to exclude from the slice. If not specified, it defaults to the length of the list.
  4. The step parameter specifies the step size between elements in the slice. If not specified, it defaults to 1.
  5. All parameters can be negative, in which case they specify the index relative to the end of the list. For example, my_list[-1] refers to the last element of the list.
  6. Slicing returns a new list that contains the specified range of elements from the original list.

You can also use slicing to access a subset of the list. Slicing allows you to extract a range of elements from the list. Here’s an example:

# Define a list
my_list = ['apple', 'banana', 'cherry', 'date', 'elderberry']

# Slice to get the first three elements
first_three = my_list[0:3] # ['apple', 'banana', 'cherry']

# Slice to get elements from index 2 to the end
from_second_onwards = my_list[2:] # ['cherry', 'date', 'elderberry']

# Slice to get the last two elements
last_two = my_list[-2:] # ['date', 'elderberry']

# Slice with a step of 2 (every second element)
every_second = my_list[::2] # ['apple', 'cherry', 'elderberry']

# Print the results
print("First three elements:", first_three)
print("From second onwards:", from_second_onwards)
print("Last two elements:", last_two)
print("Every second element:", every_second)

In the example above, we used slicing to extract a subset of the list that starts at index 0 and ends at index 3 ( not including index 3 ).

Python List Methods:

Lists in Python have many built-in methods that you can use to modify or manipulate the list. Here are some of the most commonly used methods:

  1. append() – It is used to add an element to the end of the list.
# Define a list
my_list = ['apple', 'banana', 'cherry']

# Add an element to the end of the list
my_list.append('date')

# Print the updated list
print(my_list)
  1. extend() – It is used to add the elements of another list to the end of the list or to combine two lists.
# Define a list
my_list = ['apple', 'banana']

# Extend the list with a tuple
my_list.extend(('cherry', 'date'))

# Extend the list with a set

my_list.extend({'elderberry', 'fig'})

# Print the updated list
print(my_list)
  1. insert() – It is used to insert an element at a specific position in the list.
# Define a list
my_list = ['apple', 'banana', 'cherry']

# Insert an element at index 1
my_list.insert(1, 'date')

# Print the updated list
print(my_list)

         4. remove() – It is used to remove the first occurrence of an element from the list.

# Define a list
my_list = ['apple', 'banana', 'cherry', 'banana']

# Remove the first occurrence of 'banana'
my_list.remove('banana')

# Print the updated list
print(my_list)
  1. pop() – It removes and returns the element at a specific position in the list.
# Define a list
my_list = ['apple', 'banana', 'cherry']

# Remove and return the last element
removed_element = my_list.pop()

# Print the updated list and the removed element
print("Updated list:", my_list)
print("Removed element:", removed_element)

          6. sort() – It sorts the elements of the list in ascending order.

# Define a list of numbers
my_list = [3, 1, 4, 1, 5, 9, 2, 6]

# Sort the list in descending order
my_list.sort(reverse=True)

# Print the sorted list
print(my_list)

          7 .reverse() – It reverses the order of the elements in the list.

# Define a list of strings
my_list = ['apple', 'banana', 'cherry']

# Reverse the list
my_list.reverse()

# Print the reversed list
print(my_list)
  1. clear() – It is used to remove all elements from a list, effectively emptying the list. After the clear() function is applied to a list, the list becomes empty with a length of 0.
# Define a list of strings
my_list = ['apple', 'banana', 'cherry']

# Clear all elements from the list
my_list.clear()

# Print the cleared list
print(my_list)
  1. copy() – It creates a shallow copy of a list. The shallow copy means that a new list is created with the same elements as the original list, but the elements themselves are not duplicated. Any changes made to the elements in the copied list will also affect the original list, and vice versa.
# Define a list with immutable elements
my_list = [1, 2, 3]

# Create a shallow copy of the list
my_list_copy = my_list.copy()

# Modify the copied list
my_list_copy.append(4)

# Print both lists
print("Original list:", my_list)
print("Copied list:", my_list_copy)
  1. index() – It is used to find the index of the first occurrence of a specified element within a list. If the element is not found in the list, it raises a ValueError.
# Define a list
my_list = ['apple', 'banana', 'cherry']

# Find the index of 'banana'
index_of_banana = my_list.index('banana')

# Print the index
print("Index of 'banana':", index_of_banana)
  1. count() – It is used to count the number of occurrences of a specified element in a list.
# Define a list
my_list = ['apple', 'banana', 'cherry', 'banana', 'apple']

# Count occurrences of 'banana'
banana_count = my_list.count('banana')

# Print the count
print("Count of 'banana':", banana_count)

Updating list values:

Lists in Python are mutable, and their values can be updated by using the slice and assignment the ( = ) operator.

# Define a list
my_list = [1, 2, 3, 4, 5]

# Remove elements at indices 1 to 3
my_list[1:4] = []

# Print the updated list
print(my_list)

Built-in function for Python lists:

Here are some examples of commonly used built-in functions for lists in Python:

  1. len(): It returns the length of the list.
# Define a list
my_list = [1, 2, 3, 4, 5]

# Get the length of the list
list_length = len(my_list)

# Print the length
print("Length of the list:", list_length)
  1. max(): It returns the largest element in the list.
# Define a list of numbers
my_list = [1, 5, 3, 9, 2]

# Get the largest element in the list
largest_element = max(my_list)

# Print the largest element

print("Largest element:", largest_element)
  1. min(): It returns the smallest element in the list.
# Define a list of numbers
my_list = [10, 5, 20, 3, 8]

# Get the smallest element in the list
smallest_element = min(my_list)

# Print the smallest element
print("Smallest element:", smallest_element)
  1. sum(): It returns the sum of all elements in the list.
# Define a list of numbers
my_list = [1, 2, 3, 4, 5]

# Calculate the sum of the elements in the list
total_sum = sum(my_list)

# Print the total sum
print("Sum of the list:", total_sum)

       5. sorted(): It returns a new sorted list.

# Define a list of numbers
my_list = [5, 2, 9, 1, 5, 6]

# Get a new sorted list
sorted_list = sorted(my_list)

# Print the sorted list
print("Sorted list:", sorted_list)
  1. list(): It converts an iterable to a list.
# Define a tuple
my_tuple = (1, 2, 3, 4)

# Convert the tuple to a list
my_list = list(my_tuple)

# Print the list
print("List from tuple:", my_list)

       7. any(): It returns True if at least one element in the list is True.

# Define a list of Boolean values
my_list = [False, False, True, False]

# Check if any element is True
result = any(my_list)

# Print the result
print("Any True in the list:", result)
  1. all(): It returns True if all elements in the list are True.
# Define a list of Boolean values
my_list = [True, True, True]

# Check if all elements are True
result = all(my_list)

# Print the result
print("All True in the list:", result)

        9. enumerate(): It returns an iterator that contains tuples of (index, element) pairs.

# Define a list
my_list = ['apple', 'banana', 'cherry']

# Use enumerate to get index and element
for index, element in enumerate(my_list):
print(f"Index: {index}, Element: {element}")
  1. zip(): It returns an iterator that aggregates elements from multiple lists into tuples.
# Define two lists
list1 = [1, 2, 3]
list2 = ['a', 'b', 'c']

# Use zip to combine them into tuples
zipped = zip(list1, list2)

# Convert the zipped object to a list and print
zipped_list = list(zipped)
print(zipped_list)

        11.reversed(): It returns a reverse iterator that can be used to iterate over a list in reverse order.

# Define a list
my_list = [1, 2, 3, 4, 5]

# Convert the reversed iterator to a list
reversed_list = list(reversed(my_list))

# Print the reversed list
print(reversed_list)

Iterating over a list

We can use a for loop to iterate over the list elements. Here’s an example:

# Define a list of fruits
fruits = ['apple', 'banana', 'cherry', 'date']

# Use a for loop to iterate over the list
for fruit in fruits:
print(fruit)

Membership operator in list

We can use operator (i.e. in or not in) on list elements. If an element is in list then it returns True. If an element is not in list it return False. Here’s an example:

# Example list
fruits = ['apple', 'banana', 'cherry', 'date']

# Using 'in' to check if an element is in the list
print('apple' in fruits) # Output: True
print('orange' in fruits) # Output: False


# Using 'not in' to check if an element is not in the list
print('grape' not in fruits) # Output: True
print('banana' not in fruits)
# Output: False

Repetition on list

We can use (*) operator for repetition of list. Here’s an example:

# Example list
fruits = ['apple', 'banana', 'cherry']

# Using * operator for repetition
repeated_list = fruits * 3

print(repeated_list)
# Output: ['apple', 'banana', 'cherry', 'apple', 'banana', 'cherry', 'apple', 'banana', 'cherry']

Concatenation on list

We can use (+) operator for concatenation of list. Here’s an example:

# Example lists
list1 = ['apple', 'banana']
list2 = ['cherry', 'date']

# Using + operator for concatenation
combined_list = list1 + list2

print(combined_list)
# Output: ['apple', 'banana', 'cherry', 'date']

List Comprehension

List comprehension is a concise and expressive way of creating lists in Python. It allows you to define a list and its elements within a single line of code, combining the functionality of a for loop, optional if conditions, and even nested loops. List comprehensions are preferred for their readability and efficiency compared to traditional for loops.

  1. Simple For Loop List Comprehension:

This type of list comprehension is used to create a list by iterating over elements from an iterable (e.g., list, tuple, string) without any filtering or conditions. Here’s an example:

# Example list
numbers = [1, 2, 3, 4, 5]

# List comprehension without filtering or conditions
new_list = [num for num in numbers]

print(new_list) # Output: [1, 2, 3, 4, 5]
  1. Loop and If Condition List Comprehension:

This type of list comprehension includes an if condition to filter elements while iterating over the iterable. Only elements that satisfy the condition are included in the new list. Here’s an example:

# Example list
numbers = [1, 2, 3, 4, 5, 6]

# List comprehension with an if condition
even_numbers = [num for num in numbers if num % 2 == 0]

print(even_numbers) # Output: [2, 4, 6]
  1. Loop and If-Else Condition List Comprehension:

This type of list comprehension allows you to perform different operations based on the if-else condition while iterating over the iterable. Here’s an example:

# Example list
numbers = [1, 2, 3, 4, 5, 6]

# List comprehension with if-else condition
result = ['Even' if num % 2 == 0 else 'Odd' for num in numbers]

print(result)
# Output: ['Odd', 'Even', 'Odd', 'Even', 'Odd', 'Even']
  1. Nested Loop List Comprehension:

This type of list comprehension allows you to use nested loops for creating more complex lists by iterating over multiple iterables simultaneously. Here’s an example:

# Example nested loops
colors = ['red', 'green', 'blue']
objects = ['ball', 'box', 'pen']

# List comprehension with nested loops
combinations = [f"{color} {obj}" for color in colors for obj in objects]

print(combinations)
# Output: ['red ball', 'red box', 'red pen', 'green ball', 'green box', 'green pen', 'blue ball', 'blue box', 'blue pen']

Shallow Copy and Deep Copy of Lists in Python:

In Python, when dealing with lists or other compound data structures, understanding the concepts of shallow copy and deep copy is crucial. Both concepts involve creating a new copy of an existing list, but they differ in how they handle nested objects within the list.

  1. Shallow Copy:

A shallow copy of a list creates a new list object but does not create copies of the elements inside the list. Instead, it copies references to the original objects. This means that changes made to nested objects within the copied list will affect the original list, and vice versa. To perform a shallow copy, you can use the `copy()` method or the slicing notation `[:]`. Example of Shallow Copy:

import copy

# Original list with a nested list
original_list = [[1, 2, 3], [4, 5, 6]]

# Shallow copy using the copy() method
shallow_copy1 = original_list.copy()

# Shallow copy using slicing notation
shallow_copy2 = original_list[:]

# Modifying a nested element in the copied list
shallow_copy1[0][0] = 99

print("Original List:", original_list)
# Output: Original List: [[99, 2, 3], [4, 5, 6]]

print("Shallow Copy 1:", shallow_copy1)
# Output: Shallow Copy 1: [[99, 2, 3], [4, 5, 6]]

print("Shallow Copy 2:", shallow_copy2)
# Output: Shallow Copy 2: [[99, 2, 3], [4, 5, 6]]
  1. Deep Copy:

A deep copy of a list creates a new list object and also recursively creates copies of all the nested objects within the original list. In other words, the copied list and its nested objects are entirely independent of the original list and its nested objects. To perform a deep copy, you need to use the `deepcopy()` function from the `copy` module. Example of Deep Copy:

import copy

# Original list with nested lists
original_list = [[1, 2, 3], [4, 5, 6]]

# Creating a deep copy
deep_copy = copy.deepcopy(original_list)

# Modifying a nested element in the deep copy
deep_copy[0][0] = 99

print("Original List:", original_list)
# Output: Original List: [[1, 2, 3], [4, 5, 6]]

print("Deep Copy:", deep_copy)
# Output: Deep Copy: [[99, 2, 3], [4, 5, 6]]

Shallow copy is faster and suitable when you want to create a new list but share references to nested objects. Deep copy is appropriate when you need an entirely independent copy of the original list and all its nested objects.

Python String

Python String Tutorials

Introduction:

A string is a sequence of characters. In Python, you can define a string using either single quotes () or double quotes (), or triple quotes (”’ or “””) for multiline strings. Here are some examples:

Python string features:

  1. Immutable: Strings in Python are immutable, meaning that once a string is created, its contents cannot be changed. If you want to modify a string, you need to create a new string with the desired changes.
  2. Sequence of Characters: Strings are a sequence of individual characters. Each character in a string is assigned an index, starting from 0 for the first character. This allows you to access and manipulate specific characters within a string using indexing and slicing operations.
  3. Unicode Support: Python strings support Unicode, allowing you to work with characters from different languages, including non-ASCII characters. This enables you to handle and process text in various encodings and writing systems.
  4. Concatenation: Strings can be concatenated using the “+” operator, allowing you to combine multiple strings into a single string. For example, “Hello” + ” ” + “World” results in the string “Hello World”.
  5. Length: You can obtain the length of a string using the `len()` function, which returns the number of characters in the string. This is useful for determining the size of a string or iterating over its characters.
  6. String Formatting: Python provides various methods for formatting strings. This includes the use of placeholders or format specifiers, such as `%` operator or the `format()` method, to insert variables or values into a string with specified formatting.
  7. String Operations and Methods: Python offers a wide range of built-in operations and methods specifically designed for working with strings. These include operations like string concatenation, repetition, and membership checks, as well as methods for case conversion, substring searching, replacing, splitting, stripping, and more.
  8. Escape Sequences: Strings in Python support escape sequences, which allow you to include special characters that are difficult to type directly. For example, using `n` represents a newline character, `t` represents a tab character, and `”` represents a double quote character within a string.
  9. String Comparison: Strings can be compared using operators such as `==`, `!=`, `<`, `>`, `<=`, and `>=`. Comparison is performed based on lexicographic (dictionary) ordering of characters, which compares each corresponding character’s Unicode value.
  10. String Iteration: Python allows you to iterate over a string using loops, enabling you to process each character individually or perform operations on the entire string.

Python string advantages:

  1. Versatility: Python strings are versatile and widely used for handling and manipulating text-based data. They can store and process alphanumeric characters, symbols, and even Unicode characters, making them suitable for various applications and internationalization needs.
  2. Immutable Nature: Python strings are immutable, meaning their contents cannot be changed once they are created. This immutability ensures the integrity of strings and prevents accidental modifications, making them reliable for operations like string matching, hashing, or as keys in dictionaries.
  3. Extensive String Methods: Python provides a rich set of built-in string methods that offer a wide range of operations. These methods allow you to perform tasks like searching, replacing, splitting, joining, formatting, case conversion, and more. The extensive set of string methods simplifies complex string manipulation tasks and saves you time and effort.
  4. Unicode Support: Python strings have excellent support for Unicode, making them capable of representing characters from various writing systems, including non-ASCII characters. This allows you to work with and process text in different languages and encodings, making Python strings suitable for internationalization and multilingual applications.
  5. String Formatting: Python offers flexible and powerful string formatting capabilities. With techniques like the `%` operator or the `format()` method, you can easily insert variables or values into a string with specified formatting. This makes it convenient for generating dynamic strings, constructing messages, or formatting output.
  6. String Interpolation: Python 3.6 and later versions introduce f-strings, which provide a concise and readable way to embed expressions within string literals. This feature, known as string interpolation, simplifies the process of combining variables and expressions with strings, improving code readability and reducing the need for concatenation.
  7. Compatibility with File Operations: Python strings integrate seamlessly with file handling operations. You can read or write strings to files, manipulate file paths as strings, and use string methods to parse or manipulate file content. This compatibility makes it easier to work with text files and perform file-related operations.
  8. Regular Expressions: Python’s `re` module offers support for regular expressions, providing powerful pattern matching and text manipulation capabilities. Regular expressions allow you to search for specific patterns, extract information, or perform complex text transformations, making them valuable for tasks like data validation, parsing, and text processing.
  9. Consistency and Familiarity: Python strings follow consistent syntax and behavior across different operations and methods. This consistency, combined with Python’s focus on readability and simplicity, makes working with strings in Python intuitive and easy for developers who are familiar with the language.
  10. Extensive Community and Documentation: Python is a widely adopted programming language, and as a result, there is a vast community of developers and extensive documentation available for working with strings. You can find libraries, tutorials, and resources to help with advanced string manipulation, handling special cases, or optimizing string-related operations.

Python string disadvantages:

  1. Immutability: While immutability can be an advantage in terms of data integrity, it can also be a disadvantage when it comes to efficiency. Since strings are immutable, any operation that involves modifying a string, such as concatenation or replacing characters, requires creating a new string object. This can be inefficient, especially when dealing with large strings or performing many operations.
  2. Memory Overhead: Each individual character in a Python string requires memory to store its Unicode value and other metadata. This fixed overhead per character can consume significant memory, especially when working with large strings or processing large amounts of text data. In scenarios with memory constraints, this overhead can become a limiting factor.
  3. Difficulty with Mutable Operations: Some string manipulation tasks, such as inserting or removing characters at specific positions, can be cumbersome and inefficient due to the immutability of strings. Achieving such operations often requires creating new string objects or converting the string to a mutable data structure like a list, performing the operation, and then converting it back to a string.
  4. Comparison Complexity: Comparing strings for equality or sorting them can have time complexity proportional to the length of the strings being compared. In cases where string comparison or sorting is a critical performance factor, more efficient data structures or algorithms, like tries or radix sort, might be more suitable.
  5. Limited Unicode Support in Older Versions: While Python has excellent Unicode support, there were limitations in earlier versions (pre-Python 3) regarding Unicode handling. Older versions required explicit encoding and decoding operations when working with non-ASCII characters, which could be a source of confusion or errors.
  6. Limited Mutable String Options: While Python strings are immutable, there may be scenarios where mutable string operations are desired. Python’s built-in string methods offer limited options for in-place modification, and workarounds like converting the string to a list and back can introduce additional complexity and potential performance drawbacks.
  7. Difficulty with Low-Level Operations: Python strings abstract away low-level memory access and manipulation, which can be advantageous for most applications. However, in certain scenarios where direct byte-level or bit-level manipulation is required, Python strings may not be the most suitable data structure, and using other byte-oriented data types or libraries may be more appropriate.
  8. Performance in Heavy String Manipulation: For scenarios that involve heavy string manipulation, such as text parsing or processing large volumes of text data, Python strings may not offer the best performance. In such cases, lower-level languages or specialized text processing libraries may provide more efficient options.

Re-assign Strings:

In Python, you can reassign a string to a new value by simply assigning the new value to the variable that holds the string.  Here’s an example:

# Initial string assignment
my_string = "Hello, World!"
print("Original string:", my_string)

# Reassigning the string to a new value
my_string = "Welcome to Python!"
print("Reassigned string:", my_string)

In the example above, the first print statement outputs “Hello, World!” because my_string is initially assigned that value. Then, my_string is reassigned to “Sqatools” and the second print statement outputs the new value.

It’s important to note that strings are immutable in Python, which means that once you create a string, you cannot modify it. When you “modify” a string by, for example, concatenating two strings or removing a character, you are actually creating a new string object. Here are some examples:

# Example to demonstrate string immutability in Python

# 1. String Concatenation
greeting = "Hello"
new_greeting = greeting + ", World!"
print("Original string (after concatenation):", greeting) # Output: Hello
print("New string (concatenation result):", new_greeting) # Output: Hello, World!

# 2. String Replacement
my_string = "Hello, Python!"
new_string = my_string.replace("Python", "World")
print("\nOriginal string (after replacement):", my_string) # Output: Hello, Python!
print("New string (replacement result):", new_string) # Output: Hello, World!

# 3. String Slicing
text = "Immutable"
sliced_text = text[:3] # Taking the first three characters
print("\nOriginal string (after slicing):", text) # Output: Immutable
print("Sliced string (slicing result):", sliced_text) # Output: Imm

Deleting string:

In Python, you cannot delete individual characters in a string because strings are immutable. However, you can delete the entire string object from memory using the del statement.  Here’s an example:

In the example above, the first print statement outputs the value of my_string, which is “Hello, World!”. Then, the del statement deletes the my_string object from memory. When we try to print my_string again, we get a NameError because the variable no longer exists.

String formatting methods:

Python provides several methods for formatting strings. Here are the most commonly used methods:

  1. The % operator: This operator allows you to format strings using placeholders, which are replaced with values at runtime. Here’s an example:
# Using the % operator for string formatting
name = "Alice"
age = 25

formatted_string = "My name is %s and I am %d years old." % (name, age)
print(formatted_string)
# Output: My name is Alice and I am 25 years old.

In the example above, %s and %d are placeholders for the name and age variables, respectively. The values of these variables are provided in a tuple that follows the % operator.

  1. The str.format() method: This method allows you to format strings using placeholders that are enclosed in curly braces. Here’s an example:
# Using the str.format() method for string formatting
name = "Alice"
age = 25

formatted_string = "My name is {} and I am {} years old.".format(name, age)
print(formatted_string)
# Output: My name is Alice and I am 25 years old.

In the example above, {} is a placeholder for the name and age variables. The values of these variables are provided as arguments to the str.format() method.

  1. F-strings: It allows you to embed expressions inside placeholders that are enclosed in curly braces preceded by the f character. Here’s an example:
# Using f-strings for string formatting
name = "Alice"
age = 25

# Embedding variables directly into the string
formatted_string = f"My name is {name} and I am {age} years old."
print(formatted_string)
# Output: My name is Alice and I am 25 years old.

In the example above, the f character before the string indicates that it is an f-string. The expressions inside the curly braces are evaluated at runtime and the resulting values are inserted into the string.

String operator:

In Python, strings support several operators that can be used to perform various operations on strings. Here are some of the most commonly used string operators:

  1. Concatenation (+): The + operator can be used to concatenate two or more strings. Here’s an example:
# Using the + operator to concatenate strings
str1 = "Hello"
str2 = "World"
combined_str = str1 + " " + str2 # Adding a space between the words

print(combined_str)
# Output: Hello World
  1. Repetition (*): The * operator can be used to repeat a string a certain number of times. Here’s an example:
# Using the * operator to repeat a string
str1 = "Hello "
repeated_str = str1 * 3 # Repeating the string 3 times

print(repeated_str)
# Output: Hello Hello Hello
  1. Membership (in): The in operator can be used to check if a substring exists within a string. It returns True if the substring is found, and False otherwise. Here’s an example:
# Using the 'in' operator to check membership
sentence = "Python is awesome!"

# Checking if a substring exists within the string
substring = "Python"
result = substring in sentence

print(result)
# Output: True
  1. Indexing ([]): The [] operator can be used to access individual characters within a string. You can use a positive index to access characters from the beginning of the string, and a negative index to access characters from the end of the string. Here’s an example:
# Using the [] operator for indexing a string
my_string = "Python"

# Accessing characters using positive indices
first_char = my_string[0] # First character
last_char = my_string[5] # Last character (index 5 for "n")

print("First character:", first_char) # Output: P
print("Last character:", last_char) # Output: n

# Accessing characters using negative indices
second_last_char = my_string[-2] # Second last character (index -2 for "o")
print("Second last character:", second_last_char) # Output: o
  1. Slicing ([start:end]): The [] operator can also be used to extract a substring (or slice) from a string. The start argument specifies the starting index of the slice (inclusive), and the end argument specifies the ending index of the slice (exclusive). Here’s an example:
# Using the [] operator for string slicing
my_string = "Python Programming"

# Extracting a substring using slicing
substring = my_string[0:6] # From index 0 to 5 (6 is exclusive)
print(substring) # Output: Python
  1. Comparison (==, !=, <, <=, >, >=): The comparison operators can be used to compare two strings alphabetically. The == operator returns True if the two strings are equal, and False otherwise. The != operator returns True if the two strings are not equal, and False otherwise. The < and > operators return True if the left string is alphabetically less than or greater than the right string, respectively. The <= and >= operators return True if the left string is alphabetically less than or equal to or greater than or equal to the right string, respectively. Here’s an example:
# Comparison of strings using various operators
string1 = "Apple"
string2 = "Banana"

# Checking if the strings are equal
print(string1 == string2) # Output: False

# Checking if the strings are not equal
print(string1 != string2) # Output: True

# Checking if string1 is alphabetically less than string2
print(string1 < string2) # Output: True

# Checking if string1 is alphabetically greater than string2
print(string1 > string2) # Output: False

# Checking if string1 is alphabetically less than or equal to string2
print(string1 <= string2) # Output: True

# Checking if string1 is alphabetically greater than or equal to string2
print(string1 >= string2) # Output: False

String indexing and slicing:

Indexing:

Indexing: Each character in a string is assigned an index starting from 0. You can access a particular character in a string using its index. Here’s an example:

# Using indexing to access characters in a string
my_string = "Python"

# Accessing individual characters using their indices
first_char = my_string[0] # First character
second_char = my_string[1] # Second character
last_char = my_string[5] # Last character

print("First character:", first_char) # Output: P
print("Second character:", second_char) # Output: y
print("Last character:", last_char) # Output: n
Slicing:

You can extract a portion of a string using slicing. Slicing is done using the [] operator, with two indices separated by a colon (:) inside the brackets. Here’s an example:

# Using slicing to extract a portion of a string
my_string = "Python Programming"

# Slicing from index 0 to 6 (exclusive of index 6)
substring = my_string[0:6] # This gives 'Python'

print(substring) # Output: Python

In the example above, my_string[0:5] returns the first five characters of the string, my_string[:5] returns all the characters up to the fifth character, and my_string[-5:] returns the characters from the fifth-last to the last character.

Note that the first index in a slice is inclusive and the second index is exclusive. So, my_string[0:5] returns characters from index 0 to index 4, but not the character at index 5.

In addition to the two indices separated by a colon, you can also add a third index to specify the step value. Here’s an example:

# Using slicing with a step
my_string = "Python Programming"

# Extracting every second character from index 0 to index 12
substring = my_string[0:13:2] # From index 0 to 12, taking every second character

print(substring) # Output: Pto rg

String functions:

  1. `len()`: Returns the length of a string. Here’s an example:
# Using len() to get the length of a string
my_string = "Python Programming"

# Get the length of the string
length = len(my_string)

print("The length of the string is:", length) # Output: 18
  1. `lower()`: Converts all characters in a string to lowercase. Here’s an example:
# Using lower() to convert string to lowercase
my_string = "Python Programming"

# Convert the string to lowercase
lowercase_string = my_string.lower()

print("Original string:", my_string) # Output: Python Programming
print("Lowercase string:", lowercase_string) # Output: python programming
  1. `upper()`: Converts all characters in a string to uppercase. Here’s an example:
# Using upper() to convert string to uppercase
my_string = "Python Programming"

# Convert the string to uppercase
uppercase_string = my_string.upper()

print("Original string:", my_string) # Output: Python Programming
print("Uppercase string:", uppercase_string) # Output: PYTHON PROGRAMMING
  1. `title()`: Capitalizes the first character of each word in a string. Here’s an example:
# Using title() to capitalize the first character of each word
my_string = "python programming is fun"

# Convert the string to title case
title_string = my_string.title()

print("Original string:", my_string) # Output: python programming is fun
print("Title case string:", title_string) # Output: Python Programming Is Fun
  1. `capitalize()`: Capitalizes the first character of a string. Here’s an example:
# Using capitalize() to capitalize the first character of a string
my_string = "python programming"

# Capitalize the first character
capitalized_string = my_string.capitalize()

print("Original string:", my_string) # Output: python programming
print("Capitalized string:", capitalized_string) # Output: Python programming
  1. `swapcase()`: Swaps the case of all characters in a string. Here’s an example:
# Using swapcase() to swap the case of all characters in a string
my_string = "Python Programming"

# Swap the case of all characters
swapped_string = my_string.swapcase()

print("Original string:", my_string) # Output: Python Programming
print("Swapped case string:", swapped_string) # Output: pYTHON pROGRAMMING
  1. `count()`: Returns the number of occurrences of a substring in a string. Here’s an example:
# Using count() to count occurrences of a substring
my_string = "Python programming is fun. Python is easy to learn."

# Count the occurrences of the word "Python"
count_python = my_string.count("Python")

print("Occurrences of 'Python':", count_python) # Output: 2
  1. `find()`: Returns the index of the first occurrence of a substring in a string. Here’s an example:
# Using find() to find the index of the first occurrence of a substring
my_string = "Python programming is fun."

# Find the index of the first occurrence of "Python"
index_python = my_string.find("Python")

print("Index of 'Python':", index_python) # Output: 0
  1. `rfind()`: Returns the index of the last occurrence of a substring in a string.
# Using rfind() to find the index of the last occurrence of a substring
my_string = "Python programming is fun. Python is easy to learn."

# Find the index of the last occurrence of "Python"
last_index_python = my_string.rfind("Python")

print("Index of the last 'Python':", last_index_python) # Output: 36

       10. `index()`: Like `find()`, but raises a `ValueError` if the substring is not found.

# Using index() to find the index of the first occurrence of a substring
my_string = "Python programming is fun."

# Find the index of the first occurrence of "Python"
index_python = my_string.index("Python")

print("Index of 'Python':", index_python) # Output: 0
  1. `rindex()`: Like `rfind()`, but raises a `ValueError` if the substring is not found.
# Using rindex() to find the index of the last occurrence of a substring
my_string = "Python programming is fun. Python is easy to learn."

# Find the index of the last occurrence of "Python"
last_index_python = my_string.rindex("Python")

print("Index of the last 'Python':", last_index_python) # Output: 36
  1. `startswith()`: Returns `True` if a string starts with a specified prefix, otherwise `False`.
# Using startswith() to check if the string starts with a specified prefix
my_string = "Python programming is fun."

# Check if the string starts with "Python"
starts_with_python = my_string.startswith("Python")

print("Starts with 'Python':", starts_with_python) # Output: True
  1. `endswith()`: Returns `True` if a string ends with a specified suffix, otherwise `False`.
# Using endswith() to check if the string ends with a specified suffix
my_string = "Python programming is fun."

# Check if the string ends with "fun."
ends_with_fun = my_string.endswith("fun.")

print("Ends with 'fun.':", ends_with_fun) # Output: True
  1. `replace()`: Replaces all occurrences of a substring with another substring.
# Using replace() to replace all occurrences of a substring
my_string = "Python is fun. Python is awesome."

# Replace "Python" with "Java"
new_string = my_string.replace("Python", "Java")

print("Original string:", my_string)
print("New string:", new_string)

       15. `strip()`: Removes whitespace (or other characters) from the beginning and end of a string.





  1. `rstrip()`: Removes whitespace (or other characters) from the end of a string.
# Using rstrip() to remove trailing whitespace
my_string = "Hello, world! "

# Remove the trailing whitespace
new_string = my_string.rstrip()

print("Original string:", repr(my_string))
print("New string:", repr(new_string))
  1. `lstrip()`: Removes whitespace (or other characters) from the beginning of a string.
# Using lstrip() to remove leading whitespace
my_string = " Hello, world!"

# Remove the leading whitespace
new_string = my_string.lstrip()

print("Original string:", repr(my_string))
print("New string:", repr(new_string))
  1. `split()`: Splits a string into a list of substrings using a specified delimiter.
# Using split() to split a string into a list of words
my_string = "Python is fun!"

# Split the string by whitespace (default behavior)
words = my_string.split()

print("List of words:", words)
  1. `rsplit()`: Splits a string from the right into a list of substrings using a specified delimiter.
# Using rsplit() to split a string from the right
my_string = "Python is fun and Python is awesome"

# Split the string by whitespace from the right
words = my_string.rsplit()

print("List of words:", words)

The separator used is the comma, which is passed as an argument to the rsplit() method. The 1 argument is used to specify that only one splitting should occur, which in this case splits the last fruit from the first two. Finally, we print the list of fruits.

       20. `join()`: Joins a list of strings into a single string using a specified delimiter.

# Joining with a space
words = ["Hello", "world", "Python", "rocks!"]
sentence = " ".join(words)
print(sentence) # Output: "Hello world Python rocks!"

# Joining with a comma
items = ["apple", "banana", "cherry"]
csv_line = ",".join(items)
print(csv_line) # Output: "apple,banana,cherry"

# Joining with a hyphen
letters = ["a", "b", "c", "d"]
hyphenated = "-".join(letters)
print(hyphenated) # Output: "a-b-c-d"
  1. `isalnum()`: Returns `True` if a string contains only alphanumeric characters, otherwise `False`.
# String with only letters and numbers
print("Hello123".isalnum()) # Output: True

# String with only letters
print("Python".isalnum()) # Output: True

# String with only numbers
print("2024".isalnum()) # Output: True

# String with a space
print("Hello World".isalnum()) # Output: False

# String with special characters
print("Hello@123".isalnum()) # Output: False

# Empty string
print("".isalnum()) # Output: False
  1. `isalpha()`: Returns `True` if a string contains only alphabetic characters, otherwise `False`.
# String with only letters
print("Python".isalpha()) # Output: True

# String with a space
print("Hello World".isalpha()) # Output: False

# String with numbers
print("Python3".isalpha()) # Output: False

# String with special characters
print("Hello!".isalpha()) # Output: False

# Empty string
print("".isalpha()) # Output: False

  1. `isdigit()`: Returns `True` if a string contains only digits, otherwise `False`.
# String with only digits
print("12345".isdigit()) # Output: True

# String with letters
print("123abc".isdigit()) # Output: False

# String with a space
print("123 456".isdigit()) # Output: False

# Empty string
print("".isdigit()) # Output: False
  1. `islower()`: Returns `True` if all characters in a string are lowercase, otherwise `False`.
# All lowercase letters
print("hello".islower()) # Output: True

# Mixed case
print("Hello".islower()) # Output: False

# Digits and special characters are ignored
print("hello123!".islower()) # Output: True

# Contains an uppercase letter
print("helloWorld".islower()) # Output: False

# Empty string
print("".islower()) # Output: False

      25. `isupper()`: Returns `True` if all characters in a string are uppercase, otherwise `False`.

# All uppercase letters
print("HELLO".isupper()) # Output: True

# Mixed case
print("Hello".isupper()) # Output: False

# Includes digits and symbols
print("HELLO123!".isupper()) # Output: True

# Contains a lowercase letter
print("HELLOworld".isupper()) # Output: False

# Empty string
print("".isupper()) # Output: False
  1. `istitle()`: Returns `True` if a string is titlecased (i.e., the first character of each word is capitalized), otherwise `False`.
# Title-cased string
print("Hello World".istitle()) # Output: True

# Mixed case
print("Hello world".istitle()) # Output: False

# Uppercase string
print("HELLO WORLD".istitle()) # Output: False

# Lowercase string
print("hello world".istitle()) # Output: False

# Single title-cased word
print("Python".istitle()) # Output: True
  1. `isspace()`: Returns `True` if a string contains only whitespace characters, otherwise `False`.
# Only spaces
print(" ".isspace()) # Output: True

# Only tabs
print("\t\t".isspace()) # Output: True

# Newline characters
print("\n\n".isspace()) # Output: True

# Mixed whitespace characters
print(" \t\n".isspace()) # Output: True

# Empty string
print("".isspace()) # Output: False
  1. `maketrans()`: Creates a translation table to be used with the `translate()` function.
# Mapping characters 'a' -> '1', 'b' -> '2', 'c' -> '3'
trans_table = str.maketrans("abc", "123")
text = "abcde"
print(text.translate(trans_table)) # Output: "123de"
  1. `translate()`: Returns a copy of a string with specified characters replaced.
# Create a translation table to replace 'a' -> '1', 'b' -> '2', 'c' -> '3'
trans_table = str.maketrans("abc", "123")
text = "abcde"
print(text.translate(trans_table)) # Output: "123de"
  1. `zfill()`: Pads a numeric string with zeros on the left until the specified width is reached.
# Example using zfill() to pad a string with leading zeros
number = "42"
padded_number = number.zfill(5)

print(padded_number) # Output: '00042'
  1. `expandtabs()`: Replaces tabs in a string with spaces.
# Example using expandtabs() to replace tabs with spaces
text = "Hello\tWorld\tPython"
expanded_text = text.expandtabs(4) # Replaces tabs with 4 spaces

print(expanded_text) # Output: 'Hello World Python'
  1. `encode()`: Encodes a string using a specified encoding.
# Encoding a string using UTF-8
my_string = "hello world"
encoded_string = my_string.encode("utf-8")

print(encoded_string) # Output: b'hello world'

In the example above, we have a string containing the phrase “hello world”. We then use the encode() method to encode the string using the UTF-8 encoding. The resulting encoded string is a bytes object, which is denoted by the “b” prefix in the output.

  1. `format_map()`: Formats a string using a dictionary.
# Using format_map() to format a string using a dictionary
person = {"name": "Alice", "age": 30}

# Format string using the dictionary
formatted_string = "My name is {name} and I am {age} years old.".format_map(person)

print(formatted_string)
  1. `isdecimal()`: Returns `True` if a string contains only decimal characters, otherwise `False`.
# Using isdecimal() to check if a string contains only decimal characters
my_string = "12345"

# Check if the string contains only decimal characters
is_decimal = my_string.isdecimal()

print(is_decimal) # Output: True
  1. `isnumeric()`: Returns `True` if a string contains only numeric characters, otherwise `False`.
# Using isnumeric() to check if a string contains only numeric characters
my_string = "12345"

# Check if the string is numeric
is_numeric = my_string.isnumeric()

print(is_numeric) # Output: True
  1. `partition()`:It split the string into parts based on the first occurrence of the substring.
# Using partition() to split a string based on the first occurrence of a substring
my_string = "Hello, world! Welcome to Python."

# Split the string at the first occurrence of ","
result = my_string.partition(",")

print(result)

Python Loops

Python Loops Tutorial

Introduction:

Loops are a fundamental concept in programming that allow you to repeatedly execute a block of code. In Python, there are mainly two types of loops: the for loop and the while loop.

Python loop features:

  1. Iteration: Loops in Python allow for iteration, which means executing a block of code repeatedly. This is useful when you need to perform the same operation multiple times.
  2. Loop Variables: In a `for` loop, you can define a loop variable that takes on each item from a sequence or iterable in each iteration. This allows you to perform operations on each item individually.
  3. Range-based Loops: Python provides the `range()` function, which generates a sequence of numbers that can be used with loops. It allows you to specify the start, end, and step size for the sequence.
  4. Loop Control Statements: Python loops offer control statements such as `break`, `continue`, and `pass` to modify the loop’s behavior.

    – `break` terminates the loop prematurely, and control transfers to the next statement outside the loop.

   – `continue` skips the remaining code in the current iteration and moves on to the next iteration.

   – `pass` is a placeholder statement that does nothing. It can be used when a statement is required syntactically, but you want to skip its execution.

  1. Nested Loops: Python allows nesting loops, meaning you can have loops within loops. This is useful for performing complex iterations or dealing with multi-dimensional data structures.
  2. While Loops: In addition to `for` loops, Python also supports `while` loops. While loops continue to execute a block of code as long as a given condition is true.
  3. Flexibility: Python loops provide flexibility and versatility in controlling the flow of execution. You can incorporate conditional statements, iterate over various data structures, and control the loop’s behavior using control statements.

Python loop advantages:

  1. Code Reusability: Loops allow you to write reusable code by performing repetitive tasks or operations on multiple elements or data. Instead of writing the same code multiple times, you can encapsulate it within a loop and iterate over the desired elements.
  2. Efficient Data Processing: Loops enable you to process large amounts of data or perform computations on collections of elements. By iterating over data structures like lists, tuples, or dictionaries, you can access and manipulate each item individually.
  3. Automation: Loops are essential for automating tasks and actions that need to be performed repeatedly. You can automate processes such as data parsing, file handling, or web scraping by utilizing loops to iterate over data sources or execute a series of actions.
  4. Dynamic Iteration: Python loops allow for dynamic iteration, where the number of iterations is determined during runtime. For example, you can use loops to iterate over a user-provided range of values or until a specific condition is met. This flexibility makes Python loops adaptable to various scenarios.
  5. Nested Looping: Python supports nested loops, allowing you to iterate over multiple dimensions or levels of data structures. This capability is useful when working with multi-dimensional arrays, matrices, or nested lists, as it allows you to process each element in a structured and organized manner.
  6. Control Flow: Python loops provide control flow statements such as `break`, `continue`, and `pass`. These statements offer greater control over the loop’s behavior and allow you to alter the normal flow of execution based on specific conditions. This flexibility enhances the efficiency and effectiveness of your code.
  7. Readability and Maintainability: Python’s syntax and indentation structure contribute to the readability and maintainability of loops. The clear and concise syntax makes it easier to understand and debug code that involves loops. Additionally, loops can be easily modified or extended, making them more maintainable in the long run.

Python loop disadvantages:

  1. Performance Impact: Depending on the complexity of the loop and the number of iterations, Python loops can sometimes be slower compared to other approaches such as vectorized operations or using built-in functions like `map()` or `filter()`. This can impact performance when dealing with large datasets or computationally intensive tasks.
  2. Nested Loops and Complexity: Nested loops, while providing flexibility, can result in increased code complexity. Managing multiple levels of iteration can make the code harder to read, understand, and maintain. It may also lead to potential bugs or errors, especially when dealing with larger nested loops.
  3. Inefficient Iteration over Large Data: When iterating over large data structures, such as lists or dictionaries, Python loops may not be the most efficient option. Certain operations like appending to a list within a loop can result in quadratic time complexity, leading to slower execution.
  4. Lack of Parallelization: Python loops typically execute sequentially, one iteration after another. This means they do not naturally lend themselves to parallelization or taking advantage of multiple processor cores. For computationally intensive tasks, parallelizing the code using techniques like multiprocessing or concurrent programming may be more efficient.
  5. Infinite Loop Possibility: In `while` loops, there is a risk of accidentally creating an infinite loop if the exit condition is not correctly defined or updated within the loop. This can lead to program freezing or consuming excessive resources.
  6. Code Duplication: Loops can sometimes lead to code duplication, especially if similar loop structures are used in different parts of the codebase. This duplication can make code maintenance more challenging, as changes or bug fixes may need to be applied to multiple sections.
  7. Readability Challenges: Complex loop structures or deeply nested loops may reduce code readability, particularly for those who are less familiar with Python or the specific codebase. It is important to strike a balance between using loops for efficiency and maintaining code clarity.

Python loop types:

  1. For loop: A `for` loop is used to iterate over a sequence (such as a list, tuple, string, or range) or any iterable object. It executes a set of statements for each item in the sequence. Here’s the syntax of a `for` loop in Python:




The loop variable (`item` in the example) takes on each item from the sequence in each iteration, allowing you to perform operations on it. The loop continues until all items in the sequence have been processed. Here’s an example of a `for` loop that prints each element in a list:





  1. While loop: A `while` loop is used to repeatedly execute a block of code as long as a certain condition is true. It continues iterating until the condition becomes false. Here’s the syntax of a `while` loop in Python:




The loop checks the condition before each iteration. If the condition is true, the code block is executed. The loop continues until the condition evaluates to false. Here’s an example of a `while` loop that prints numbers from 1 to 5:





In this example, the loop continues as long as the value of `count` is less than or equal to 5. The variable ‘count’ is incremented by 1 in each iteration.

Python loop control statement:

  1. Break statement: The `break` statement is used to exit a loop prematurely. When encountered inside a loop, the `break` statement immediately terminates the loop and transfers control to the next statement outside the loop. Here’s an example that uses a `break` statement to stop a loop when a certain condition is met:




In this example, the loop iterates over the `numbers` list. When the value of `value ` becomes 4, the `break` statement is encountered, causing the loop to terminate immediately.

  1. Continue statement: The `continue` statement is used to skip the remaining code inside a loop for the current iteration and move on to the next iteration. It allows you to bypass certain iterations based on a condition. Here’s an example that uses a `continue` statement to skip printing even numbers:




In this example, the loop iterates over the `numbers` list. When an even number is encountered (`value % 2 == 0`), the `continue` statement is executed, and the remaining code inside the loop is skipped for that iteration.

  1. Pass statement: The `pass` statement is a placeholder statement that does nothing. It is used when a statement is syntactically required, but you want to skip its execution. It can be used inside loops to create empty loops or as a placeholder for future code. Here’s an example that uses a `pass` statement inside a loop:




In this example, the loop iterates five times, but since there is no code inside the loop, it effectively does nothing.

These loop control statements provide flexibility and control over the execution flow within loops. They help in handling specific conditions or terminating loops when necessary.

Conditional statement with python loops:

  1. For loop – We can use conditional statements within a Python `for` loop to perform different actions based on specific conditions. Here’s an example:




In this example, we have a list of fruits. Within the `for` loop, we use conditional statements (`if`, `elif`, and `else`) to check the value of each `fruit` variable.

– If the `fruit` is ‘banana’, it will print “I like bananas!”.

– If the `fruit` is ‘apple’, it will print “Apples are my favorite”.

– For any other fruit, it will print “I enjoy eating” followed by the name of the fruit.

The `if` statement checks if the condition is true, and if it is, the corresponding code block is executed. The `elif` statement allows for additional conditions to be checked, and the `else` statement provides a default action when none of the previous conditions are true.

  1. While loop – We can use conditional statements within a Python `while` loop to control the loop’s execution based on specific conditions. Here’s an example:




In this example, we have a `while` loop that continues until the `count` variable reaches 6. Within the loop, we use a conditional statement (`if`) to check if the `count` is equal to 2.

– If the `count` is 2, it will print “Skipping count 2”, and then use the `continue` statement to skip the remaining code in the loop for that iteration and move on to the next iteration.

– For any other value of `count`, it will print “Current count:” followed by the value of `count`.

By updating the value of `count` within the loop, we ensure that the loop eventually terminates when the condition `count <= 5` becomes false.

Python DataTypes

Introduction :

In Python, every value has a specific data type associated with it. Data types define the nature of the variables, objects, or values you can work with in your code. Understanding different data types is crucial for effective programming. Let’s explore the commonly used data types in Python.

Numeric Types:

  • Integer (int): Represents whole numbers without decimal points.

In Python, the integer data type (int) represents whole numbers without any decimal points. Integers can be positive or negative, and they have no limit on their size, allowing you to work with both small and large numbers.

Example:

num1 = 10
  • Floating-Point (float): Represents decimal numbers.

In Python, the float data type represents decimal numbers. Floats are used to represent real numbers, including both positive and negative values. Unlike integers, floats can have decimal points and can represent numbers with fractional parts.

Example:

num2 = 3.14
  • Complex (complex): Represents numbers with real and imaginary parts.

In Python, the complex data type represents numbers with both real and imaginary parts. Complex numbers are often used in mathematical and scientific computations that involve complex arithmetic operations.

Example:

num3 = 4 + 5j

Sequence Types:

  • String (str): Represents a sequence of characters enclosed in quotes.

In Python, a string is a sequence of characters enclosed in single quotes (‘ ‘) or double quotes (” “). Strings are immutable, which means once created, they cannot be modified. However, you can create new strings based on existing ones.

In Python, a string is a sequence of characters enclosed in single quotes (‘ ‘) or double quotes (” “). Strings are immutable, which means once created, they cannot be modified. However, you can create new strings based on existing ones.

Example:

name = "John"
  • List (list): Represents an ordered collection of items enclosed in square brackets.

In Python, a list is a versatile and mutable data type that represents an ordered collection of items. Lists can contain elements of different data types, such as numbers, strings, or even other lists. Lists are denoted by square brackets [ ].

Example:

numbers = [1, 2, 3, 4, 5]
  • Tuple (tuple): Represents an ordered collection of items enclosed in parentheses.

In Python, a tuple is an ordered collection of elements, similar to a list. However, unlike lists, tuples are immutable, meaning they cannot be modified once created. Tuples are typically denoted by parentheses ( ) or can be created without any delimiters.

Example:

coordinates = (10, 20)

Dictionary (dict):

Represents a collection of key-value pairs enclosed in curly braces.

In Python, a dictionary is an unordered collection of key-value pairs. It is also known as an associative array or a hash map. Dictionaries are enclosed in curly braces { }, and each item in the dictionary is represented as a key-value pair separated by a colon (:).

Example:

person = {"name": "John", "age": 25, "city": "New York"}

Set Types:

Set (set): Represents an unordered collection of unique items enclosed in curly braces.

In Python, a set is an unordered collection of unique elements. Sets are denoted by curly braces { }. Each element in a set must be unique, and duplicate values are automatically removed. Sets are mutable, meaning you can modify them after creation.

Example:

fruits = {"apple", "banana", "orange"}

Boolean Type:

Boolean (bool): Represents either True or False.

In Python, the Boolean data type represents truth values. A Boolean value can be either True or False. Booleans are often used for logical operations and comparisons.

In Python, the keywords True and False (with the first letter capitalized) are used to represent Boolean values.

Example:

is_active = True
is_admin = False

Datatype Conversion:

Below is a table that demonstrates the conversion of various Python data types into other data types. Each entry in the table includes the original data type, the target data type, a code snippet to perform the conversion, and an example output.

Integer(int) : Convert int Data Type to all other Data Type.

Data TypeTarget Data TypeCodeOutput


int

floatnum_int = 10  

num_float = float(num_int)
10.0


int

strnum_int = 42

num_str = str(num_int)
’42’


int

complexnum_int = 5  

num_complex = complex(num_int)
(5+0j)


int

listnum_int = 123  

num_list = list(num_int)
TypeError: ‘int’ object is not iterable  
Conversion is not possible


int

dictnum_int = 1  

num_dict = dict(num_int)
TypeError: ‘int’ object is not iterable
Conversion is not possible


int

tuplenum_int = 7  

num_tuple = tuple(num_int)
TypeError: ‘int’ object is not iterable
Conversion is not possible
intboolnum_int = 0
num_bool = bool(num_int)
print(num_bool)  

num_int1 = 123
num_bool1 = bool(num_int1)
print(num_bool1)
False


True


Float: Convert Float Data Type to all other Data Type.

Data Type Target Data Type Code Output
floatintnum_float = 10.5  

num_int = int(num_float)
10
float

str

num_float = 3.14  

num_str = str(num_float)
‘3.14’
float

complex

num_float = 3.0  
num_complex = complex(num_float,4.5)
(3+4.5j)
float
list

num_float = 3.14  
num_list = list(num_float)
TypeError: ‘int’ object is not iterable   Conversion is not possible
float
dict

num_float = 2.5  
num_dict = dict(num_float)
TypeError: ‘int’ object is not iterable   Conversion is not possible
floattuple
num_float = 1.5  
num_tuple = float(num_float)
TypeError: ‘int’ object is not iterable   Conversion is not possible
floatboolnum_int = 0
num_bool = bool(num_int)
print(num_bool)  

num_int1 = 12.3
num_bool1 = bool(num_int1)
print(num_bool1)
False


True

Complex : Convert complex data type to all other data type.

Data Type Target Data TypeCodeOutput
complexintnum_complex = complex(3, 4)
 
num_int = int(num_complex)

TypeError: int() argument must be a string, a bytes-like object or a real number, not ‘complex’   Conversion is not possible.
complexfloat
i).
num_complex = complex(3, 4)
num_float = float(num_complex)


ii).
num_complex = complex(3, 4)
num_float = float(num_complex.real)
i).TypeError: float() argument must be a string or a real number, not ‘complex’   Conversion is not possible.



ii).  3
complexstr

num_complex = complex(1, 2)<br>num_str = str(num_complex)

‘(1+2j)’
complexlist
num_complex = complex(2, 3)

num_list = [num_complex.real, num_complex.imag]
[2.0, 3.0]
complexdict
num_complex = complex(2, 1)  

num_dict = {‘real’: num_complex.real, ‘imag’: num_complex.imag}
{‘real’: 2.0, ‘imag’: 1.0}
complextuple
num_complex = complex(4, 5)

num_tuple = (num_complex.real, num_complex.imag)
(4.0, 5.0)
complexbool
num_complex = complex(0, 0)  

num_bool = bool(num_complex)
False

String(str) : Convert str data type to all other data type.

Data TypeTarget Data TypeCodeOutput

str
int
num_str = ‘987’  

num_int = int(num_str)
987

str
float
num_str = ‘2.71’  

num_float = float(num_str)
2.71

str
complex
num_str = ‘1+2j’  

num_complex = complex(num_str)
(1+2j)

str
list
str_val = ‘hello’  

list_val = list(str_val)
[‘h’, ‘e’, ‘l’, ‘l’, ‘o’]

str
dict
str_val = ‘hello’  

dict_val = {str_val: len(str_val)}
{‘hello’: 5}

str
tuple
str_val = ‘abc’  

tuple_val = tuple(str_val)
(‘a’, ‘b’, ‘c’)

str
bool
str_val = ‘True’  

bool_val = bool(str_val)
True

List(list) : Convert list data type to all other data type.

Data TypeTarget Data Type CodeOutput
listint
num_list = [1, 2, 3]  

num_int = int(”.join(map(str, num_list)))
123
listfloat
num_list = [3, 1, 4]  

num_float = float(”.join(map(str, num_list)))
314.0
liststr
num_list = [10, 20, 30]  

num_str = ‘, ‘.join(map(str, num_list))
’10, 20, 30′
listcomplex
num_list = [2, 3]  

num_complex = complex(num_list[0], num_list[1])
(2+3j)
listdict
num_list = [1, 2]  

num_dict = dict(zip(num_list, [‘one’, ‘two’]))
{1: ‘one’, 2: ‘two’}
listtuple
num_list = [7, 8, 9]  

num_tuple = tuple(num_list)
(7, 8, 9)
listbool
num_list = [0, 1, 0]  

num_bool = any(num_list)
True

Tuple(tuple) : Convert tuple data type to all other data type.

Data Type Target Data Type Code Output
tupleint
num_tuple = (4, 5, 6)  

num_int = int(”.join(map(str, num_tuple)))
456
tuplefloat
num_tuple = (1, 2)  

num_float = float(‘.’.join(map(str, num_tuple)))
1.2
tuplestr
num_tuple = (7, 8, 9)  

num_str = ‘, ‘.join(map(str, num_tuple))
‘7, 8, 9’
tuplecomplex
num_tuple = (3, 4)  

num_complex = complex(num_tuple[0], num_tuple[1])
(3+4j)
tuplelist
num_tuple = (10, 20)  

num_list = list(num_tuple)
[10, 20]
tupledict
num_tuple = (‘x’, 1)  

num_dict = dict([num_tuple])
{‘x’: 1}
tuplebool
num_tuple = (0, 0)  

num_bool = any(num_tuple)
False

Dictionary(dict) : Convert dict data type to all other data type.

Data Type Target Data Type Code Output
ictint
num_dict = {‘a’: 1}  

num_int = int(list(num_dict.keys())[0])
97
dictfloat
num_dict = {‘pi’: 3.14}  

num_float = float(list(num_dict.values())[0])
3.14
dictstr
num_dict = {1: ‘one’}  

num_str = str(list(num_dict.keys())[0])
‘1’
dictcomplex
num_dict = {3: 5}
 
num_complex = complex(list(num_dict.keys())[0], list(num_dict.values())[0])
(3+5j)
dictlist
num_dict = {‘a’: 1, ‘b’: 2}  

num_list = list(num_dict.items())
[(‘a’, 1), (‘b’, 2)]
dicttuple
num_dict = {‘x’: 10, ‘y’: 20}  

num_tuple = tuple(num_dict.items())
((‘x’, 10), (‘y’, 20))
dictbool
num_dict = {‘flag’: True}  

num_bool = bool(list(num_dict.values())[0])
True

Set : Convert set data type to all other data type.

Data Type Target Data Type CodeOutput
setint
num_set = {1, 2, 3}  

num_int = int(”.join(map(str, num_set)))
123
setfloat
num_set = {3, 1, 4}  

num_float = float(”.join(map(str, num_set)))
314.0
setstr
num_set = {10, 20, 30}  

num_str = ‘, ‘.join(map(str, num_set))
’10, 20, 30′
setcomplex
num_set = {2, 3}  

num_complex = complex(list(num_set)[0], list(num_set)[1])
(2+3j)
setlist
num_set = {1, 2, 3}  

num_list = list(num_set)
[1, 2, 3]
setdict
num_set = {1, 2, 3}  

num_dict = dict.fromkeys(num_set, ‘value’)
{1: ‘value’, 2: ‘value’, 3: ‘value’}
settuple
num_set = {7, 8, 9)  

num_tuple = tuple(num_set)
(8, 9, 7)
setbool
num_set = set()  

num_bool = bool(num_set)
False

Boolean(bool) : Convert bool data type to all other data type.

Data TypeTarget Data Type CodeOutput
boolint
num_bool = False  

num_int = int(num_bool)
0
boolfloat
num_bool = True  

num_float = float(num_bool)
1.0
boolstr
num_bool = True  

num_str = str(num_bool)
‘True
boolcomplex
num_bool = True  

num_complex = complex(int(num_bool), 0)
(1+0j)
boollist
num_bool = False  

num_list = [int(num_bool)]
[0]
booldict
num_bool = True  

num_dict = {str(num_bool): ‘boolean’}
{‘True’: ‘boolean’}
booltuple
num_bool = False  

num_tuple = (int(num_bool),)
(0,)

Python Conditional Statements

Introduction:

In Python, the if-else statement allows you to execute different blocks of code based on certain conditions. It provides a way to make decisions and control the flow of your program.

The basic syntax of an if-else statement in Python is as follows:

if condition:
    # Code block to execute if the condition is True
else:
    # Code block to execute if the condition is False

The condition is an expression that evaluates to either True or False. If the condition is True, the code block immediately following the if statement will be executed. Otherwise, if the condition is False, the code block following the else statement will be executed.

Let’s look at an example to understand it better. Suppose we want to check whether a given number is positive or negative:

number = int(input("Enter a number: "))
if number > 0:
    print("The number is positive.")
else:
    print("The number is negative or zero.")

In this example, we use the input() function to get a number from the user, convert it to an integer using int(), and store it in the number variable. The if-else statement then checks whether the number is greater than zero. If it is, it prints “The number is positive.” Otherwise, it prints “The number is negative or zero.”

You can also use multiple if-else statements together to handle more complex conditions. Here’s an example that checks whether a number is positive, negative, or zero:

number = int(input("Enter a number: "))
if number > 0:
    print("The number is positive.")
elif number < 0:
    print("The number is negative.")
else:
    print("The number is zero.")

In this case, the elif statement allows us to check an additional condition. If the first condition is False, it moves to the elif statement and checks whether the number is less than zero. If that condition is True, it prints “The number is negative.” Finally, if both the first and second conditions are False, it executes the code block under the else statement and prints “The number is zero.”

Python conditional statement features:

  1. `if` statement: The `if` statement is the fundamental building block of a conditional statement. It allows you to execute a block of code if a certain condition is true. The syntax of the `if` statement is as follows:
if condition:
        # Code block to execute if the condition is True
  1. `else` statement: The `else` statement is used in conjunction with the `if` statement. It provides an alternative block of code to execute when the condition in the `if` statement is false. The syntax is as follows:
if condition:
       # Code block to execute if the condition is True
   else:
       # Code block to execute if the condition is False
  1. `elif` statement: The `elif` statement allows you to check additional conditions after an initial `if` statement. It provides a way to handle multiple cases within the same conditional statement. The syntax is as follows:
if condition1:
       # Code block to execute if condition1 is True
   elif condition2:
       # Code block to execute if condition1 is False and condition2 is True
   else:
       # Code block to execute if all conditions are False
  1. Nested conditional statements: Python allows you to nest if-else statements within other if-else statements. This means that you can have if-else statements inside the code blocks of other if-else statements. This feature enables handling more complex conditions and creating decision trees.
  2. Logical operators: Python provides logical operators such as `and`, `or`, and `not` that allow you to combine multiple conditions. These operators can be used within the condition of an if statement to create more complex conditions.
  3. Ternary operator: Python supports a ternary operator, which provides a concise way to write conditional expressions in a single line. The syntax is as follows:
value_if_true if condition else value_if_false

This operator allows you to assign a value based on a condition without writing a full if-else statement.

Python conditional statements advantages:

  1. Decision-making: Conditional statements provide a way to make decisions in your Python programs. They allow you to execute different blocks of code based on the evaluation of specific conditions. This enables your program to respond dynamically to different situations and perform different actions as needed.
  2. Flexibility: Conditional statements provide flexibility in controlling the flow of your program. By using conditions, you can define different paths or branches of execution based on varying inputs or states. This flexibility allows you to handle diverse scenarios and customize the behavior of your program accordingly.
  3. Code organization: Using conditional statements helps in organizing your code. By dividing your code into blocks based on conditions, you can make it more structured and readable. Each block of code within a conditional statement represents a specific case or behavior, making it easier to understand the logic and purpose of different parts of your program.
  4. Error handling: Conditional statements are often used for error handling and exception handling in Python. By checking certain conditions, you can identify and handle specific error scenarios or exceptional cases appropriately. This allows you to anticipate and respond to errors or unexpected inputs, improving the overall robustness of your program.
  5. Code efficiency: Conditional statements can help optimize your code by selectively executing relevant blocks of code based on conditions. This can reduce unnecessary computations or operations, improving the efficiency and performance of your program. For example, you can include conditional checks to avoid executing resource-intensive code when certain conditions are not met.
  6. Complex decision trees: With the ability to nest conditional statements and combine logical operators, you can create complex decision trees in Python. This allows you to handle intricate conditions and multiple cases effectively. By structuring your code in this manner, you can handle a wide range of possibilities and make your programs more adaptable to diverse scenarios.

Python conditional statement disadvantages:

  1. Code complexity: As the number of conditions and branches increases, conditional statements can make the code more complex and harder to understand. Nested if-else statements or multiple elif conditions can make the code difficult to follow and maintain, leading to potential bugs or errors.
  2. Code duplication: In certain cases, conditional statements can result in code duplication. If similar blocks of code need to be executed in different branches of the conditional statements, you may end up duplicating that code, which can lead to maintenance issues. Code duplication can make it harder to update or modify the logic consistently across multiple branches.
  3. Readability and maintainability: While conditional statements can provide flexibility, excessive or poorly organized conditional logic can decrease code readability and maintainability. If the conditional statements become too complex or nested, it may become challenging for other developers (including yourself in the future) to understand the code and make modifications.
  4. Potential for errors: The use of conditional statements introduces the possibility of logical errors, such as incorrect conditions or unintended behavior due to missing conditions. It’s important to carefully design and test the conditions to ensure they cover all relevant cases and produce the expected results.
  5. Scalability: Conditional statements may become less scalable when handling a large number of conditions or cases. If the number of conditions grows significantly, maintaining and extending the conditional logic can become cumbersome. In such cases, alternative approaches, such as using dictionaries or lookup tables, may be more appropriate to handle complex mappings or decision-making.
  6. Code coupling: Conditional statements can introduce tight coupling between different parts of your code, especially if the conditions rely on specific variables or states. This can make it harder to modify or refactor your code in the future without affecting other parts of the program.

Python conditional statement – If statement:

In Python, the if statement allows you to execute a block of code only if a certain condition is true. It provides a way to make decisions and control the flow of your program.The basic syntax of an if statement in Python is as follows:

age = 20

if age >= 18:
    print("You are an adult.")

The `condition` is an expression that evaluates to either `True` or `False`. If the condition is `True`, the code block immediately following the `if` statement will be executed. Otherwise, if the condition is `False`, the code block will be skipped, and the program will continue with the next line of code. Here’s an example:

temperature = 30

if temperature > 25:
    print("It's a hot day!")
print("Enjoy your day.")

In this example, we use the `input()` function to get a number from the user, convert it to an integer using `int()`, and store it in the `number` variable. The if statement then checks whether the number is greater than zero. If it is, it executes the code block under the if statement and prints “The number is positive.”

Python conditional statement – If-else statement:

In Python, the if-else statement allows you to execute different blocks of code based on certain conditions. It provides a way to make decisions and control the flow of your program. The basic syntax of an if-else statement in Python is as follows:

if condition:
    # code to execute if condition is true
else:
    # code to execute if condition is false

The `condition` is an expression that evaluates to either `True` or `False`. If the condition is `True`, the code block immediately following the `if` statement will be executed. Otherwise, if the condition is `False`, the code block following the `else` statement will be executed. Here’s an example:

score = 75

if score >= 60:
    print("Congratulations, you passed!")
else:
    print("Sorry, you failed.")

In this example, we use the `input()` function to get a number from the user, convert it to an integer using `int()`, and store it in the `number` variable. The if-else statement then checks whether the number is greater than zero. If it is, it executes the code block under the `if` statement and prints “The number is positive.” Otherwise, if the number is not greater than zero, it executes the code block under the `else` statement and prints “The number is negative or zero.”

Python conditional statement – elif statement:

In Python, the `elif` statement allows you to check additional conditions after an initial `if` statement. It provides a way to handle multiple cases and execute different blocks of code based on the conditions. The basic syntax of an `elif` statement in Python is as follows:

if condition1:
    # code to execute if condition1 is true
elif condition2:
    # code to execute if condition2 is true
else:
    # code to execute if neither condition1 nor condition2 is true

You can have as many `elif` statements as needed to handle different conditions. The conditions are evaluated one by one, from top to bottom. If a condition is `True`, the corresponding code block will be executed, and the remaining conditions will be skipped. If none of the conditions are `True`, the code block under the `else` statement will be executed. Here’s an example:

temperature = 45

if temperature > 85:
    print("It's really hot outside.")
elif temperature > 70:
    print("It's warm outside.")
elif temperature > 55:
    print("It's cool outside.")
elif temperature > 32:
    print("It's cold outside.")
else:
    print("It's freezing outside!")

In this example, we use the `input()` function to get the student’s score, convert it to an integer using `int()`, and store it in the `score` variable. The `elif` statements check the score against different ranges to determine the letter grade. If the score is greater than or equal to 90, it assigns the grade ‘A’. If the score is between 80 and 89, it assigns ‘B’, and so on. If none of the conditions are met, it assigns ‘F’ as the grade. Finally, we print the grade using the `print()` function.

Python nested conditional statement – nested if-else statements:

In Python, nested if-else statements allow you to have if-else statements within other if-else statements. They provide a way to handle complex conditions and execute different blocks of code based on multiple conditions. The basic syntax of a nested if-else statement in Python is as follows:

if condition1:
    # code to execute if condition1 is true
    if condition2:
        # code to execute if condition1 and condition2 true
    else:
        # code execute if condition1 true but condition2 false
else:
    # code to execute if condition1 is false

In a nested if-else statement, the inner if-else statement is indented further to the right than the outer if-else statement. The inner if-else statement is evaluated only if the condition of the outer if statement is `True`. Here’s an example:

age = 25
has_membership = True

if age >= 18:
    if has_membership:
        print("Welcome to the exclusive club!")
    else:
        print("Membership required for entry.")
else:
    print("You must be 18 or older to enter.")

In this example, we use the `input()` function to get the student’s score and whether they earned extra credit. The `elif` statements check the score against different ranges to determine the letter grade. However, the grade also depends on whether the student earned extra credit.

If the score is greater than or equal to 90, it checks the `credit` variable. If it is ‘yes’, it assigns the grade ‘A+’. Otherwise, it assigns ‘A’.

Similarly, for scores between 80 and 89, it checks the `credit` variable to assign either ‘B+’ or ‘B’.

If none of the conditions are met, it assigns ‘F’ as the grade.

Finally, we print the grade using the `print()` function.

Python If else Practice Programs

Python Variables

Introduction:

Variables are an important concept in any programming language, including Python. In simple language, a variable is a named location in memory that stores a value. In Python, you can use variables to store any type of data, including numbers, strings, and even complex data structures like lists and dictionaries.

Creating Variables in Python:

To create a variable in Python, you need to give it a name and assign a value to it. Here’s an example:

Name = “ Omkar “
Age = 25
Profession = “Software Engineer “

In the example above, we created three variables: Name, Age, and Profession.
     1.  The name variable is a string.
     2.  The age variable is an integer.
     3.  The Profession variable is also a string.

Python Variable Naming Rules:

When creating variables in Python, there are a few rules that you need to follow:
1). Variable names must start with a letter or underscore (_), followed by any combination of letters, digits, and underscores.
2). Variable names are case-sensitive, which means name and Name are two different variables.
3). A variable name cannot start with a number.
4). A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ ).

Python Variables Types:

1. Numbers – Consists of integers, floating-point numbers, and complex numbers.
2. Strings – Consists of characters in quotes.
3. Booleans – Consists of True or False values.
4. Lists – Consists of ordered sequences of elements.
5. Tuples – Consists of ordered, immutable sequences of elements.
6. Sets – Consists of unordered collections of unique elements.
7. Dictionaries – Consists of unordered collections of key-value pairs.

Checking Types of the Variable:

First, we will create some variables.

Name = “ Omkar “
Age = 25
Height = 5.8 ft

To check the type of the variable use the type() function.

print(type(Name))    # Output: <class ‘str’>
print(type(Age))          # Output: <class ‘int’>
print(type(Height))      # Output: <class ‘float’>

To check the address of the variable use the id() function.

print(id(Name))      # Output: 2623848788368
print(id(Age)) # Output: 140718085367336
print(id(Height)) # Output: 2623846066576

Value Assignment:

To assign the value to a variable use equal sign ( = ).
Example:
A = 10
We can also assign same value to multiple variables.
A = B = C = 10

Multiple Value Assignment:

We can assign different values to different variables at the same time. We separate the variables and their values by commas ‘,’.

Example:
a, b, c = 40, 50, 60
Here,
Value of variable a is 40 , b is 50 and c is 60.

Scope of Variable:

In Python, the scope of a variable determines where in the code the variable can be accessed and used. The scope of a variable is defined by where the variable is created and assigned a value.
There are two types of variable scopes in Python: global scope and local scope.

1. Global Scope:
Variables created outside of any function or class have a global scope. This means that they can be accessed and modified from anywhere in the code, including within functions and classes.
Example:

number = 100         # global variable

def print_number():
print(number) # accessing global variable

def modify_number():
global number # declaring number as global variable
number = 200 # modifying global variable

print_number() # Output: 100
modify_number()
print_number() # Output: 200

In the example above, the variable number is declared outside of any function, so it has a global scope. The function print_number() can access and print the value of number, and the function modify_number() can modify the value of number by declaring it as a global variable using the global keyword.

2. Local Scope:
Variables created inside a function or class have a local scope. This means that they can only be accessed and modified within that function or class.
Example:

def my_function():
number = 100 # local variable
print(number) # accessing local variable

my_function() # Output: 100
print(number) # NameError: name 'number' is not defined

Basic Mathematical Operations Using Variables:

Creating variables and assigning value to them:
a, b = 10 , 20

Performing operations and printing output:

print(a+b) # Addition       Output: 30
print(a-b) # Subtraction Output: -10
print(a*b) # Multiplication Output: 200
print(a/b) # Division Output: 0.5

Conclusion:

In conclusion, variables are an important concept in Python programming language. They allow you to store and manipulate data in your code, and are important for writing effective programs. By understanding how to create, name, and use variables, you can write Python code that is easy to read, maintain.

NumPy MCQ : Set 6

Python NumPy MCQ

1). What is the output of the following code?

				
					import numpy as np
x = np.array([[4, 8, 0], [2, 0, 6]])
print("Number of non-zero elements: ", np.count_nonzero(x))
				
			

a) 4
b) 5
c) 6
d) 7

Correct answer is: a) 4
Explanation: The given code imports the NumPy library and creates a 2-dimensional NumPy array `x` with the elements [[4, 8, 0], [2, 0, 6]]. The `np.count_nonzero()` function is then used to count the number of non-zero elements in the array `x`.

2). What is the output of the following code?

				
					import numpy as np
x = np.array([[5, 3],
              [7, 4]])
print("Median of array:", np.median(x))
				
			

a) 3
b) 4
c) 5
d) 6

Correct answer is: b) 4.5
Explanation: The given code imports the NumPy library and creates a 2-dimensional NumPy array `x` with the elements [[5, 3], [7, 4]]. The `np.median()` function is then used to calculate the median of all elements in the array `x`.

3). What is the output of the following code?

				
					import numpy as np
x = np.array([[5, 3], [7, 4]])
print("Median of array along row:", np.median(x, axis=0))
				
			

a) [5, 3]
b) [7, 4]
c) [6, 3.5]
d) [4, 5]

Correct answer is: c) [6, 3.5]
Explanation: The given code imports the NumPy library and creates a 2-dimensional NumPy array `x` with the elements [[5, 3], [7, 4]]. The `np.median()` function is then used to calculate the median of the array along the rows, which means the median is computed for each column.

4). What is the output of the following code?

				
					import numpy as np
x = np.array([[5, 3], [7, 4]])
print("Median of array along column:", np.median(x, axis=1))
				
			

a) [4.0, 3.5]
b) [3.5, 4.0]
c) [3.0, 5.5]
d) [5.5, 3.0]

Correct answer is: a) [4.0, 5.5]
Explanation: The given code imports the NumPy library and creates a 2-dimensional NumPy array `x` with the elements [[5, 3], [7, 4]]. The `np.median()` function is then used to calculate the median along the column (axis 1) of the array `x`.

5). What is the purpose of the following code?

				
					import numpy as np
x = np.array([[4, 8, 0], [2, 0, 6]])

for ele in np.nditer(x):
    print(ele, end=' ')
				
			

a) It prints the elements of the 2-dimensional NumPy array `x`.
b) It calculates the sum of all elements in the 2-dimensional NumPy array `x`.
c) It reshapes the 2-dimensional NumPy array `x` to a 1-dimensional array.
d) It creates a new 2-dimensional array with the same elements as `x`.

Correct answer is: a) It prints the elements of the 2-dimensional NumPy array `x`.
Explanation: The given code imports the NumPy library and creates a 2-dimensional NumPy array `x` with the elements [[4, 8, 0], [2, 0, 6]]. It then uses a loop to iterate through the elements of the array `x` using the `np.nditer()` function. The `np.nditer()` function in NumPy allows iterating over all elements of an array regardless of its shape and dimensions. In the code, each element of the array `x` is printed using the loop with `print(ele, end=’ ‘)`.

6). What is the purpose of the following code?

				
					import numpy as np
x = np.array([2, 6, 3, 1])
print("Square of every element in the array: ", np.square(x))

				
			

a) It calculates the sum of all elements in the array `x`.
b) It calculates the mean of all elements in the array `x`.
c) It calculates the product of all elements in the array `x`.
d) It calculates the square of each element in the array `x`.

Correct answer is: d) It calculates the square of each element in the array `x`.
Explanation: The given code imports the NumPy library and creates a 1-dimensional NumPy array `x` with the elements [2, 6, 3, 1]. The `np.square()` function is then used to calculate the square of each element in the array `x`.

7). What is the output of the following code?

				
					import numpy as np
x = np.array([[4, 8, 0], [2, 0, 6]])
y = np.array([[5], [7]])

print(np.append(x, y, axis=1))
				
			

a) [[4, 8, 0], [2, 0, 6], [5], [7]]
b) [[4, 8, 0, 5], [2, 0, 6, 7]]
c) [[4, 5], [8, 7], [0, 0], [2, 6]]
d) [[4, 8, 0], [2, 0, 6], [5, 7]]

Correct answer is: b) [[4, 8, 0, 5], [2, 0, 6, 7]]
Explanation: The given code imports the NumPy library and creates two NumPy arrays `x` and `y`. The array `x` is a 2-dimensional array with the elements [[4, 8, 0], [2, 0, 6]]. The array `y` is a 2-dimensional array with the elements [[5], [7]]. The `np.append()` function is then used to append the array `y` to the array `x` along axis 1 (columns).

8). What is the output of the following code?

				
					import numpy as np
x = np.array([[4, 8, np.nan], [2, 4, 6]])
print("Old: \n", x)

print("New: \n", x[~np.isnan(x).any(axis=1)])
				
			

a) Old:
[[ 4. 8. nan]
[ 2. 4. 6.]]
New:
[[2. 4. 6.]]

b) Old:
[[ 4. 8. nan]
[ 2. 4. 6.]]
New:
[[4. 8. nan]]

c) Old:
[[ 4. 8. nan]
[ 2. 4. 6.]]
New:
[[4. 8. 6.]]

d) Old:
[[ 4. 8. nan]
[ 2. 4. 6.]]
New:
[[ 4. 8. nan]
[ 2. 4. 6.]]

Correct answer is: a) Old:
[[ 4. 8. nan]
[ 2. 4. 6.]]
New:
[[2. 4. 6.]]
Explanation: The given code uses NumPy to perform operations on a 2-dimensional array `x`, which contains some NaN (Not a Number) values. Let’s break down the code step by step. The code uses `np.isnan(x)` to create a boolean array, where `True` indicates the positions with NaN values in the original array. The `any(axis=1)` checks if there is any `True` in each row of the boolean array. The `~` is the logical NOT operator, which negates the boolean array. The modified array contains only the rows that do not have any NaN values. In this case, the row `[4, 8, nan]` is removed from the array, leaving only the row `[2, 4, 6]`.

9). What is the output of the following code?

				
					import numpy as np
x = np.array([3, 5, 1])
print("Magnitude of the given vector: ", np.linalg.norm(x))

				
			

a) 9
b) 3
c) 5.916079783099616
d) 35

Correct answer is: c) 5.916079783099616
Explanation: The given code imports the NumPy library and creates a 1-dimensional NumPy array `x` with the elements [3, 5, 1]. The `np.linalg.norm()` function is then used to calculate the magnitude (Euclidean norm) of the vector `x`. The magnitude of a vector is calculated as the square root of the sum of the squares of its elements.

10). What is the output of the following code?

				
					import numpy as np
x = np.array([8, 6, 7, 0, 7, 8, 6, 6])

unique, count = np.unique(x, return_counts=True)
print("Frequency of unique values in the given array:")
print(np.asarray((unique, count)))
				
			

a) [6, 7, 8, 0] [3, 2, 2, 1]
b) [0, 6, 7, 8] [1, 3, 2, 2]
c) [0, 6, 7, 8] [2, 3, 2, 1]
d) [0, 6, 7, 8] [3, 2, 1, 2]

Correct answer is: b) [0, 6, 7, 8] [1, 3, 2, 2]
Explanation: The given code imports the NumPy library and creates a 1-dimensional NumPy array `x` with the elements [8, 6, 7, 0, 7, 8, 6, 6]. The `np.unique()` function is then used with the parameter `return_counts=True` to find the unique values and their corresponding frequencies in the array `x`.

11). What is the output of the following code?

				
					import numpy as np
x = np.array([4, 8, 0])

if x.size == 0:
    print("Array is empty")
else:
    print("Array is not empty")

				
			

a) Array is empty
b) Array is not empty
c) 4 8 0
d) 3

Correct answer is: b) Array is not empty
Explanation: The given code imports the NumPy library and creates a 1-dimensional NumPy array `x` with the elements [4, 8, 0]. The code then checks the size of the array using the `x.size` attribute. Since `x` contains three elements, its size is not equal to zero. Therefore, the condition `x.size == 0` evaluates to False. As a result, the code enters the `else` block and prints “Array is not empty”.

12). What is the output of the following code?

				
					import numpy as np
x = np.array([3, 5, 1])
print("Product of the elements in the given array: ", x.prod())

				
			

a) 3
b) 15
c) 8
d) 11

Correct answer is: b) 15
Explanation: The given code imports the NumPy library and creates a 1-dimensional NumPy array `x` with the elements [3, 5, 1]. The `x.prod()` function is then used to calculate the product of all elements in the array `x`.

13). What is the purpose of the following code?

				
					import pandas as pd
import numpy as np
 
x = np.arange(1, 16).reshape(3, 5)
 
DF = pd.DataFrame(x)
DF.to_csv("data1.csv")

df = pd.read_csv("data1.csv")
print(df)
				
			

a) It generates a NumPy array with numbers from 1 to 15 and reshapes it to a 3×5 matrix, then saves it as a CSV file.
b) It reads a CSV file named “data1.csv” and prints its content as a Pandas DataFrame.
c) It generates a Pandas DataFrame from a CSV file named “data1.csv” and prints its content.
d) It converts a NumPy array to a Pandas DataFrame and saves it as a CSV file named “data1.csv”.

Correct answer is: a) It generates a NumPy array with numbers from 1 to 15 and reshapes it to a 3×5 matrix, then saves it as a CSV file.
Explanation: `import pandas as pd`: Imports the Pandas library with the alias `pd`. `import numpy as np`: Imports the NumPy library with the alias `np`. `x = np.arange(1, 16).reshape(3, 5)`: Generates a NumPy array with numbers from 1 to 15 using `np.arange()` and reshapes it to a 3×5 matrix using `reshape()` method. `DF = pd.DataFrame(x)`: Creates a Pandas DataFrame `DF` from the NumPy array `x`. `DF.to_csv(“data1.csv”)`: Saves the Pandas DataFrame `DF` as a CSV file named “data1.csv”. `df = pd.read_csv(“data1.csv”)`: Reads the CSV file “data1.csv” and creates a new Pandas DataFrame `df`. `print(df)`: Prints the content of the Pandas DataFrame `df`.

14). What is the purpose of the following code?

				
					import numpy as np
x = np.array([[6, 5, 7], [10, 9, 1], [7, 8, 2]])

for i in range(0, 2):
    print(f"{i+1} column: ", x[:, i])
				
			

a) It prints the sum of elements in each row of the array `x`.
b) It prints the transpose of the array `x`.
c) It prints the first two columns of the array `x`.
d) It prints the elements of the second row in reverse order.

Correct answer is: c) It prints the first two columns of the array `x`.
Explanation: The given code imports the NumPy library and creates a 3×3 2-dimensional NumPy array `x` with the elements. The code then uses a for loop to iterate over the columns of `x` with the range from 0 to 2 (excluding 2). For each iteration, it prints the respective column of the array `x` using the slicing syntax `x[:, i]`, where `i` is the column index.

15). What is the purpose of the following code?

				
					import numpy as np
x = np.array([[6, 5, 7], [10, 9, 1], [7, 8, 2]])
print(x[0:2, 0:2])
				
			

a) Prints the first two elements of each row.
b) Prints the first two rows and first two columns of the array.
c) Prints the first two rows and first three columns of the array.
d) Prints the first two elements of each column.

Correct answer is: b) Prints the first two rows and first two columns of the array.
Explanation: The given code imports the NumPy library and creates a 2-dimensional NumPy array `x` with the elements: The code then uses slicing to extract a sub-array from `x` using the notation `x[0:2, 0:2]`.
Slicing notation `x[0:2, 0:2]` means the following:
– `0:2` selects the first and second rows (index 0 and 1) of the array.
– `0:2` selects the first and second columns (index 0 and 1) of the array.

16). What is the output of the following code?

				
					import numpy as np
x = np.array([[6, 5, 7], [10, 9, 1], [7, 8, 2]])
print("Sum of all columns: ", x.sum(axis=0))

				
			

a) [23, 22, 10]
b) [6, 5, 7, 10, 9, 1, 7, 8, 2]
c) [17, 22, 10]
d) [23, 9, 17]

Correct answer is: a) [23, 22, 10]
Explanation: The given code imports the NumPy library and creates a 2-dimensional NumPy array `x` with the elements: The `x.sum(axis=0)` calculates the sum of all columns (along axis 0) in the array `x`.
The sum of each column is calculated as follows:
Column 1 sum: 6 + 10 + 7 = 23
Column 2 sum: 5 + 9 + 8 = 22
Column 3 sum: 7 + 1 + 2 = 10

17). What is the output of the following code?

				
					import numpy as np
x = np.array([[6, 5, np.nan], [np.nan, 9, 1], [7, 8, 2]])

temp = np.ma.masked_array(x, np.isnan(x))
print("Array after removing nan values: \n", temp)

				
			

a)
[[6.0 5.0 –]
[– 9.0 1.0]
[7.0 8.0 2.0]]

b)
[[6.0 5.0 0.0]
[0.0 9.0 1.0]
[7.0 8.0 2.0]]

c)
[[6.0 5.0 0.0]
[0.0 9.0 1.0]
[7.0 8.0 2.0]]

d)
[[6.0 5.0 1.0]
[1.0 9.0 1.0]
[7.0 8.0 2.0]]

Correct answer is: a)
[[6.0 5.0 –]
[– 9.0 1.0]
[7.0 8.0 2.0]]
Explanation: The given code creates a 2-dimensional NumPy array `x` with the elements [[6, 5, np.nan], [np.nan, 9, 1], [7, 8, 2]]. The `np.isnan()` function is used to identify the NaN (Not a Number) values in the array `x`. The `np.ma.masked_array()` function then creates a masked array where the NaN values are masked or hidden. The masked array `temp` will have the NaN values replaced with ‘–‘, representing that these values are masked and not considered in computations.

18). What is the output of the following code?

				
					import numpy as np
x = np.array([1, 2, 3])
y = np.array([4, 5, 6])

output = np.concatenate((x, y))
print("\nAfter concatenate:")
print(output)
				
			

a) [1, 2, 3, 4, 5, 6]
b) [[1, 2, 3], [4, 5, 6]]
c) [[1, 2, 3, 4, 5, 6]]
d) [5, 7, 9]

Correct answer is: a) [1, 2, 3, 4, 5, 6]
Explanation: The given code imports the NumPy library and creates two 1-dimensional NumPy arrays, `x` and `y`. The `np.concatenate()` function is then used to concatenate these two arrays. The `np.concatenate()` function concatenates arrays along a specified axis. If the axis is not specified, it defaults to 0, which means the arrays will be concatenated along the first dimension.

19). What is the purpose of the following code?

				
					import numpy as np
import pandas as pd
x = np.random.rand(6, 3)

df = pd.DataFrame(x, columns=['A', 'B', 'C'])
print("\nPandas DataFrame: ")
print(df)
				
			

a) It generates a NumPy array of random floating-point numbers with a shape of (6, 3).
b) It generates a Pandas DataFrame with 6 rows and 3 columns containing random floating-point numbers.
c) It calculates the mean of a Pandas DataFrame and prints the result.
d) It creates a Pandas DataFrame from a given NumPy array and prints the DataFrame.

Correct answer is: b) It generates a Pandas DataFrame with 6 rows and 3 columns containing random floating-point numbers.
Explanation:
1. The code imports the NumPy library as `np` and the Pandas library as `pd`.
2. The `np.random.rand(6, 3)` function generates a NumPy array of random floating-point numbers with a shape of (6, 3).
3. The `pd.DataFrame()` function takes the NumPy array `x` and converts it into a Pandas DataFrame with 6 rows and 3 columns. The columns are labeled as ‘A’, ‘B’, and ‘C’ respectively, as specified by the `columns` parameter.
4. The `print(df)` statement displays the Pandas DataFrame, showing the 6 rows and 3 columns of random floating-point numbers.

20). What is the output of the following code?

				
					import numpy as np
x = np.arange(15).reshape(3, 5)
y = np.arange(20).reshape(4, 5)

if x.shape == y.shape:
    print("Same dimensions")
else:
    print("Different dimensions")
				
			

a) Same dimensions
b) Different dimensions

Correct answer is: b) Different dimensions
Explanation: The given code imports the NumPy library and creates two NumPy arrays, `x` and `y`. The array `x` is created using `np.arange(15)` and reshaped into a 3×5 array, while the array `y` is created using `np.arange(20)` and reshaped into a 4×5 array. Next, the code checks whether the shapes of arrays `x` and `y` are equal using the `x.shape == y.shape` condition. If the shapes are equal, it prints “Same dimensions”, and if the shapes are different, it prints “Different dimensions”.

21). What is the output of the following code?

				
					import numpy as np
x = np.array([[6, 5, 7], [10, 9, 1], [7, 8, 2]])

print((~x.any(axis=0)).any())
				
			

a) True
b) False

Correct answer is: b) False
Explanation: The given code imports the NumPy library and creates a 2-dimensional NumPy array `x` with the elements [[6, 5, 7], [10, 9, 1], [7, 8, 2]]. The expression `(~x.any(axis=0))` is used to find the columns in the array `x` that contain at least one nonzero element. The `x.any(axis=0)` returns a boolean array indicating for each column whether it contains at least one nonzero element.

22). What is the output of the following code?

				
					import numpy as np
angle = np.array([45, 13])
print(f"Sin of {angle}: ", np.sin(angle))
				
			

a) [0.85090352, 0.42016704]
b) [0.52532199, 0.96355819]
c) [0.01745241, 0.85607777]
d) [0.57357644, 0.14112001]

Correct answer is: a) [0.85090352, 0.42016704]
Explanation: The given code imports the NumPy library and creates a NumPy array `angle` with the elements [45, 13]. The `np.sin()` function is then used to calculate the sine of the angles in the `angle` array. The sine of an angle in degrees can be calculated using the NumPy `sin()` function, which takes an array of angles in radians as input. To convert degrees to radians, we need to multiply the angle by π/180.

23). What is the purpose of the following code?

				
					import numpy as np
age = np.array([20, 25, 21, 23, 26, 27, 26, 30, 24, 26])

print("Standard Deviation: ", np.std(age))
				
			

a) It calculates the mean age of the given data.
b) It calculates the variance of the ages in the dataset.
c) It calculates the standard deviation of the ages in the dataset.
d) It calculates the total number of elements in the array.

Correct answer is: c) It calculates the standard deviation of the ages in the dataset.
Explanation: The given code imports the NumPy library and creates a NumPy array `age` containing the ages of a group of individuals. The `np.std()` function is then used to calculate the standard deviation of the ages in the dataset. The standard deviation is a measure of how spread out the values are from the mean. It is calculated using the formula:
Standard Deviation = sqrt((Σ (x – mean)^2) / N)
where:
– `x` represents each individual value (age) in the dataset.
– `mean` is the mean (average) of the ages.
– `N` is the total number of elements (ages) in the dataset.

24). What is the purpose of the following code?

				
					import numpy as np
arr = np.array([12.202, 90.23120, 123.88, 23.202])  
print(np.round(arr, 2))
				
			

a) It calculates the mean of the array elements.
b) It calculates the standard deviation of the array elements.
c) It rounds the array elements to the nearest integer.
d) It rounds the array elements to two decimal places.

Correct answer is: d) It rounds the array elements to two decimal places.
Explanation: The given code imports the NumPy library and creates a NumPy array `arr` with the elements [12.202, 90.23120, 123.88, 23.202]. The `np.round()` function is then used to round the elements of the array `arr` to two decimal places. The rounded array elements are as follows:
Rounded array = [12.20, 90.23, 123.88, 23.20]

25). What is the output of the following code?

				
					import numpy as np
arr = np.array([12.202, 90.23120, 123.88, 23.202])

print(np.floor(arr))
				
			

a) [12, 90, 123, 23]
b) [12.0, 90.0, 123.0, 23.0]
c) [13, 91, 124, 24]
d) [12.202, 90.231, 123.88, 23.202]

Correct answer is: a) [12, 90, 123, 23]
Explanation: The given code imports the NumPy library and creates a 1-dimensional NumPy array `arr` with the elements [12.202, 90.23120, 123.88, 23.202]. The `np.floor()` function is then used to round down each element in the array `arr` to the nearest integer.

NumPy MCQ : Set 5

Python NumPy MCQ

1). What is the output of the following code?

				
					import numpy as np
x = np.array([[5, 3],
              [7, 4]])
print("Sum of each row : ", np.sum(x, axis=1))

				
			

a) [8, 11]
b) [12, 17]
c) [6, 11]
d) [9, 14]

Correct answer is: a) [8, 11]
Explanation: The given code imports the NumPy library and creates a 2-dimensional NumPy array `x` with the elements [[5, 3], [7, 4]]. The `np.sum()` function is then used to calculate the sum of each row in the array `x` along `axis=1`.

2). What is the output of the following code?

				
					import numpy as np
x = np.array([[5, 3],
              [7, 4]])
print("Sum of each column: ", np.sum(x, axis=0))

				
			

a) [12, 7]
b) [8, 9]
c) [19, 7]
d) [5, 3, 7, 4]

Correct answer is: a) [12, 7]
Explanation: The given code imports the NumPy library and creates a 2-dimensional NumPy array `x` with the elements [[5, 3], [7, 4]]. The `np.sum()` function is then used to calculate the sum of each column in the array `x` along `axis=0`.

3). What is the output of the following code?

				
					import numpy as np
x = np.array([5, 3])
y = np.array([7, 4])
print("Inner-dot product: ", np.dot(x, y))
				
			

a) 31
b) 29
c) 39
d) 33

Correct answer is: a) 47
Explanation: The given code imports the NumPy library and creates two 1-dimensional NumPy arrays `x` and `y` with the elements [5, 3] and [7, 4] respectively. The `np.dot()` function is then used to calculate the inner-dot product of the arrays `x` and `y`.

4). What is the output of the following code?

				
					import numpy as np
x = np.array([[5, 3],
              [7, 4]])
print("Original matrix: \n", x)
vector = np.array([2, 5])
print("Vector to be added: \n", vector)

for i in range(len(x)):
    x[i, :] = x[i, :] + vector
    
print("Matrix after adding a vector: \n", x)
				
			

a)
Original matrix:
[[5 3]
[7 4]]
Vector to be added:
[2 5]
Matrix after adding a vector:
[[7 8]
[9 9]]

b)
Original matrix:
[[5 3]
[7 4]]
Vector to be added:
[2 5]
Matrix after adding a vector:
[[ 7 8]
[ 9 10]]

c)
Original matrix:
[[5 3]
[7 4]]
Vector to be added:
[2 5]
Matrix after adding a vector:
[[ 7 5]
[ 9 4]]

d)
Original matrix:
[[5 3]
[7 4]]
Vector to be added:
[2 5]
Matrix after adding a vector:
[[ 7 5]
[ 9 9]]

Correct answer is: a)
Original matrix:
[[5 3]
[7 4]]
Vector to be added:
[2 5]
Matrix after adding a vector:
[[7 8]
[9 9]]
Explanation: The given code initializes a 2-dimensional NumPy array `x` with the elements [[5, 3], [7, 4]] and a 1-dimensional NumPy array `vector` with the elements [2, 5]. The code then adds the `vector` to each row of the `x` array in a loop.

5). What is the purpose of the following code?

				
					import numpy as np
x = np.array([[3, 0],
             [6, 4]])
print("Matrix: \n", x)
y = x.tolist()
print("List: ", y)
				
			

a) The code calculates the sum of all elements in the NumPy array `x`.
b) The code converts the NumPy array `x` into a list `y`.
c) The code reshapes the NumPy array `x` into a 1-dimensional array.
d) The code transposes the rows and columns of the NumPy array `x`.

Correct answer is: b) The code converts the NumPy array `x` into a list `y`.
Explanation: The given code snippet demonstrates the use of NumPy and Python’s built-in `tolist()` function. 

6). What is the output of the following code?

				
					import numpy as np
x = np.array([[1, 5, np.nan],
              [8, np.nan, 9]])
print(np.isnan(x))
				
			

a) [[False, False, True], [False, True, False]]
b) [[True, True, False], [False, False, True]]
c) [[False, True, False], [True, False, False]]
d) [[False, False, False], [False, False, False]]

Correct answer is: a) [[False, False, True], [False, True, False]]
Explanation: The given code imports the NumPy library and creates a 2-dimensional NumPy array `x` with some elements being NaN (Not a Number). The `np.isnan()` function is then used to check if the elements in the array are NaN or not. The output of `np.isnan(x)` will be a Boolean array with the same shape as `x`, where each element is `True` if the corresponding element in `x` is NaN, and `False` otherwise.

7). What is the output of the following code?

				
					import numpy as np
x = np.array([[5, 6],
              [7, 8],
              [9, 10]])
print(x.transpose())
				
			

a) [[5, 6],
[7, 8],
[9, 10]]

b) [[5, 7, 9],
[6, 8, 10]]

c) [[5, 7, 9],
[6, 8, 10],
[9, 10]]

d) [[5, 6],
[6, 7],
[7, 8],
[8, 9],
[9, 10]]

Correct answer is: b) [[5, 7, 9],
[6, 8, 10]]
Explanation: The given code imports the NumPy library and creates a 2-dimensional NumPy array `x` with the elements [[5, 6], [7, 8], [9, 10]]. The `x.transpose()` function is then used to calculate the transpose of the array `x`. The transpose of a 2-dimensional array is obtained by flipping the rows and columns. So, the resulting array will have the elements of `x` interchanged between rows and columns.

8). What is the output of the following code?

				
					import numpy as np
x = np.array([[6, 5],
              [10, 9],
              [8, 7]])

print("Sorting matrix by row: ")
print(np.sort(x))
				
			

a) [[5 6]
[9 10]
[7 8]]
b) [[6 5]
[10 9]
[8 7]]
c) [[5 6]
[7 8]
[9 10]]
d) [[10 9]
[8 7]
[6 5]]

Correct answer is: c) [[5 6]
[7 8]
[9 10]]
Explanation: The given code imports the NumPy library and creates a 2-dimensional NumPy array `x` with the elements [[6, 5], [10, 9], [8, 7]]. The `np.sort()` function is then used to sort the elements of `x` along each row.

9). What is the output of the following code?

				
					import numpy as np
x = np.array([[6, 5],
              [10, 9],
              [8, 7]])

print("Sorting matrix by column: ")
print(np.sort(x, axis=0))
				
			

a)
[[ 5 5]
[ 8 7]
[10 9]]

b)
[[ 5 6]
[ 7 8]
[ 9 10]]

c)
[[ 6 5]
[ 9 10]
[ 7 8]]

d)
[[ 7 5]
[ 8 6]
[10 9]]

Correct answer is: b)
[[ 5 6]
[ 7 8]
[ 9 10]]
Explanation: The given code imports the NumPy library and creates a 2-dimensional NumPy array `x` with the elements [[6, 5], [10, 9], [8, 7]]. The `np.sort()` function is then used to sort the elements of the array `x` along axis 0, which means sorting along the columns.

10). What is the output of the following code?

				
					import numpy as np
x = np.array([[6, 5],
              [10, 9],
              [8, 7]])

print("Values bigger than 7 =", x[x>7])
				
			

a) Values bigger than 7 = [10, 9, 8, 7]
b) Values bigger than 7 = [10, 9, 8]
c) Values bigger than 7 = [8, 7]
d) Values bigger than 7 = [6, 5]

Correct answer is: b) Values bigger than 7 = [10, 9, 8]
Explanation: The given code imports the NumPy library and creates a 2-dimensional NumPy array `x` with the elements [[6, 5], [10, 9], [8, 7]]. The code then uses boolean indexing (`x>7`) to extract the elements from `x` that are bigger than 7.

11). What is the output of the following code?

				
					import numpy as np
x = np.array([[6, 5],
              [10, 9],
              [8, 7]])

x[x >= 7] = 0
print("New matrix")
print(x)
				
			

a) [[0, 0], [0, 0], [0, 0]]
b) [[6, 5], [10, 9], [8, 7]]
c) [[6, 5], [0, 0], [0, 0]]
d) [[0, 5], [0, 9], [0, 7]]

Correct answer is: c) [[6, 5], [0, 0], [0, 0]]
Explanation: The given code imports the NumPy library and creates a 2-dimensional NumPy array `x` with the elements [[6, 5], [10, 9], [8, 7]]. It then modifies the elements of the array `x` based on the condition `x >= 7`. Any element in the array that is greater than or equal to 7 is replaced with 0.

12). What is the purpose of the following code?

				
					import numpy as np
x = np.array([[6, 5],
              [10, 9],
              [8, 7]])
print("Original array: ", x)
print("After swapping")
new = print(x[::-1, :])
				
			

a) The code transposes the original array.
b) The code reverses the rows of the original array.
c) The code reverses the columns of the original array.
d) The code prints the original array in reverse order.

Correct answer is: b) The code reverses the rows of the original array.
Explanation: The given code imports the NumPy library and creates a 2-dimensional NumPy array `x` with the elements [[6, 5], [10, 9], [8, 7]]. It then prints the original array using `print(“Original array: “, x)`. The line `new = print(x[::-1, :])` involves array slicing. Specifically, `x[::-1, :]` reverses the rows of the original array `x`.

13). What is the output of the following code?

				
					import numpy as np
x = np.array([[6, 5],
              [10, 9],
              [8, 7]])

x[0,:] = x[0,:]*2
print("After multiplying the first row by 2: ", x)
				
			

a) [[12, 10], [10, 9], [8, 7]]
b) [[12, 10], [20, 18], [16, 14]]
c) [[6, 5], [10, 9], [8, 7]]
d) [[6, 5], [10, 9], [8, 7, 2]]

Correct answer is: a) [[12, 10], [10, 9], [8, 7]]
Explanation: The given code imports the NumPy library and creates a 2-dimensional NumPy array `x` with the elements [[6, 5], [10, 9], [8, 7]]. Next, it modifies the first row of the array `x` by multiplying it by 2.

14). What is the purpose of the following code?

				
					import numpy as np
x = np.array([[6, 5],
              [10, 9],
              [8, 7]])

x[0,:] = x[0,:] + x[1,:]
print("After addition: ", x)
				
			

a) It transposes the matrix `x`
b) It calculates the element-wise addition of the first and second rows in the matrix `x`
c) It calculates the dot product of the first and second rows in the matrix `x`
d) It reshapes the matrix `x` into a 1-dimensional array

Correct answer is: b) It calculates the element-wise addition of the first and second rows in the matrix `x`
Explanation: The given code snippet imports the NumPy library and creates a 2-dimensional NumPy array `x` with the elements [[6, 5], [10, 9], [8, 7]]. The line `x[0,:] = x[0,:] + x[1,:]` performs element-wise addition of the first row (`[6, 5]`) and the second row (`[10, 9]`) of the matrix `x`. The result is then assigned back to the first row of the matrix `x`.

15). What is the output of the following code?

				
					import numpy as np
x = np.array([6+2j, 10+5j])
print("Real part: ", x.real)
print("Imaginary part: ", x.imag)
				
			

a) Real part: [6, 10], Imaginary part: [2, 5]
b) Real part: [8, 15], Imaginary part: [2, 5]
c) Real part: [6, 10], Imaginary part: [2j, 5j]
d) Real part: [8, 15], Imaginary part: [2j, 5j]

Correct answer is: a) Real part: [6, 10], Imaginary part: [2, 5]
Explanation: The given code imports the NumPy library and creates a 1-dimensional NumPy array `x` with complex numbers: [6+2j, 10+5j]. The `real` attribute of the complex array `x` gives the real parts of the complex numbers, and the `imag` attribute gives the imaginary parts.

16). What is the output of the following code?

				
					import numpy as np
x = np.array([56, 18, 28, 36])
y = np.array([76, 36, 56])
print(np.intersect1d(x, y))

				
			

a) [56, 18, 28, 36]
b) [56, 36]
c) [18, 28, 76]
d) [76, 18, 28]

Correct answer is: b) [56, 36]
Explanation: The given code imports the NumPy library and creates two 1-dimensional NumPy arrays, `x` and `y`, with the elements [56, 18, 28, 36] and [76, 36, 56] respectively. The `np.intersect1d()` function is then used to find the intersection of the elements between the arrays `x` and `y`.

17). What is the output of the following code?

				
					import numpy as np
x = np.array([25, 33, 10, 45, 33, 10])
print(np.unique(x))
				
			

a) [10, 25, 33, 45]
b) [10, 33, 45]
c) [25, 33, 10, 45]
d) [25, 33, 10]

Correct answer is: a) [10, 25, 33, 45]
Explanation: The given code imports the NumPy library and creates a 1-dimensional NumPy array `x` with the elements [25, 33, 10, 45, 33, 10]. The `np.unique()` function is then used to find the unique elements in the array `x`.

18). What is the output of the following code?

				
					import numpy as np
x = np.array([56, 18, 28, 36])
y = np.array([76, 36, 56])

print(np.setdiff1d(x, y))
				
			

a) [56, 18, 28, 36]
b) [18, 28]
c) [76]
d) [18, 28, 76]

Correct answer is: b) [18, 28]
Explanation: The given code imports the NumPy library and creates two 1-dimensional NumPy arrays, `x` and `y`, with the elements [56, 18, 28, 36] and [76, 36, 56], respectively. The `np.setdiff1d()` function is then used to find the set difference between the arrays `x` and `y`. The set difference between two arrays contains the elements that are present in the first array but not in the second array.

19). What is the output of the following code?

				
					import numpy as np
x = np.array([56, 18, 28, 36])
y = np.array([76, 36, 56, 90])

print(np.union1d(x, y))
				
			

a) [18, 28, 36, 56, 76, 90]
b) [56, 18, 28, 36, 76, 90]
c) [56, 18, 28, 36]
d) [18, 28, 36, 76, 90]

Correct answer is: a) [18, 28, 36, 56, 76, 90]
Explanation: The given code imports the NumPy library and creates two 1-dimensional NumPy arrays, `x` and `y`, with the elements [56, 18, 28, 36] and [76, 36, 56, 90] respectively. The `np.union1d()` function is then used to find the unique values that are in either of the arrays. The union of `x` and `y` will contain all the unique elements present in both arrays, without any duplicates. The output will be a new sorted 1-dimensional array with these unique elements.

20). What is the output of the following code?

				
					import numpy as np
x = np.array([76, 36, 56, 90])
print("Index of maximum Values: ", np.argmax(x))
				
			

a) 0
b) 1
c) 2
d) 3

Correct answer is: d) 3
Explanation: The given code imports the NumPy library and creates a 1-dimensional NumPy array `x` with the elements [76, 36, 56, 90]. The `np.argmax()` function is then used to find the index of the maximum value in the array `x`.

21). What is the output of the following code?

				
					import numpy as np
x = np.array([76, 36, 56, 90])
print("Index of maximum Values: ", np.argmin(x))
				
			

a) 1
b) 2
c) 3
d) 4

Correct answer is: b) 2
Explanation: The given code imports the NumPy library and creates a 1-dimensional NumPy array `x` with the elements [76, 36, 56, 90]. The `np.argmin()` function is then used to find the index of the minimum value in the array `x`.

22). What is the output of the following code?

				
					import numpy as np
x = np.array([[4, 8, 7], [2, 3, 6]])
print("Fifth element: ", x[1, 1])
				
			

a) 4
b) 8
c) 3
d) 6

Correct answer is: c) 3
Explanation: The given code imports the NumPy library and creates a 2-dimensional NumPy array `x` with the elements [[4, 8, 7], [2, 3, 6]]. In NumPy arrays, indexing starts from 0. The expression `x[1, 1]` accesses the element at the second row and second column of the array `x`.

23). What is the output of the following code?

				
					
import numpy as np
x = np.zeros((2, 1, 3))
print("After removing single-dimensional entries: ", np.squeeze(x).shape)
				
			

a) (2, 1, 3)
b) (2, 3)
c) (1, 3)
d) (3,)

Correct answer is: b) (2, 3)
Explanation: The given code imports the NumPy library and creates a 3-dimensional NumPy array `x` with the shape (2, 1, 3) filled with zeros. The `np.squeeze()` function is then used to remove single-dimensional entries from the array `x`. The `np.squeeze()` function removes any dimensions from the array that have a size of 1. In this case, the second dimension has a size of 1, so it is removed from the array. Before squeezing, the shape of `x` is (2, 1, 3), which means it has 2 elements along the first dimension, 1 element along the second dimension, and 3 elements along the third dimension. After squeezing, the shape becomes (2, 3) because the second dimension with a size of 1 is removed. Therefore, the correct answer is (2, 3).

24). What is the output of the following code?

				
					import numpy as np
x = np.array((3, 8, 5))
y = np.array((4, 0, 7))
z = np.column_stack((x, y))
print(z)
				
			

a) [[3, 4], [8, 0], [5, 7]]
b) [[3, 8, 5], [4, 0, 7]]
c) [[3, 8], [4, 0], [5, 7]]
d) [[4, 3], [0, 8], [7, 5]]

Correct answer is: a) [[3, 4], [8, 0], [5, 7]]
Explanation: The given code imports the NumPy library and creates two 1-dimensional NumPy arrays `x` and `y` with the elements (3, 8, 5) and (4, 0, 7) respectively. Then, the `np.column_stack()` function is used to stack the arrays `x` and `y` column-wise, forming a new 2-dimensional array `z`.

25). What is the output of the following code?

				
					import numpy as np
x = np.arange(1, 11)
print("Original array:", x)
print("After splitting:")
print(np.split(x, [2, 5]))
				
			

a) Original array: [1 2 3 4 5 6 7 8 9 10]
After splitting: [array([1, 2]), array([3, 4, 5]), array([ 6, 7, 8, 9, 10])]

b) Original array: [1 2 3 4 5 6 7 8 9 10]
After splitting: [array([1, 2]), array([3, 4, 5, 6]), array([7, 8, 9, 10])]

c) Original array: [1 2 3 4 5 6 7 8 9 10]
After splitting: [array([1, 2]), array([3, 4, 5]), array([6, 7, 8, 9, 10])]

d) Original array: [1 2 3 4 5 6 7 8 9 10]
After splitting: [array([1, 2]), array([3, 4]), array([5, 6, 7, 8, 9, 10])]

Correct answer is: a) Original array: [1 2 3 4 5 6 7 8 9 10]
After splitting: [array([1, 2]), array([3, 4, 5]), array([ 6, 7, 8, 9, 10])]
Explanation: The given code imports the NumPy library and creates a 1-dimensional NumPy array `x` with the elements [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]. The `np.split()` function is then used to split the array into subarrays. The `np.split(x, [2, 5])` function call splits the array `x` at the indices [2, 5]. It means the array will be split into three subarrays: from index 0 to index 2 (exclusive), from index 2 to index 5 (exclusive), and from index 5 to the end of the array.