sdfsd7
sdfsd7
In python module can be defined as a python program file which contains a python code including
python functions, class, or variables. In other words, we can say that our python code file saved with
the extension (.py) is treated as the module.
Modules in Python provides us the flexibility to organize the code in a logical way. To use the
functionality of one module into another, we must have to import the specific module.
Creating Module
Example: demo.py
# Python Module example
def sum(a,b):
return a+b
def sub(a,b):
return a-b
def mul(a,b):
return a*b
def div(a,b):
return a/b
In the above example we have defined 4 functions sum(), sub(), mul() and div() inside a module
named demo.
Loading the module in our python code
We need to load the module in our python code to use its functionality. Python provides two types of
statements as defined below.
1. import statement
2. from-import statement
Python Modules
Python modules are a great way to organize and reuse code across different programs. Think of a
module as a file containing Python code that defines functions, classes, and variables you can use in
your own programs. By importing these modules, you can make use of their functionality without
having to rewrite code.
“Modules” in Python are files that contain Python code. It can contain functions, classes, and
variables, and you can use them in your scripts. It help to reuse code and keep the project organized.
Tuple
A tuple in Python is a collection of elements that is ordered and immutable. Tuples are created using
parentheses () and can also hold elements of different data types.
Example:
my_tuple = (1, 'banana', False)
print(my_tuple)
Advantages:
Immutable – Elements cannot be changed after creation.
Faster access time compared to lists for read-only operations.
Disadvantages:
Cannot be modified once created.
Use Cases and Applications:
Used for fixed collections of elements where immutability is desired.
Returning multiple values from a function.
Set
A set in Python is a collection of unique elements that is unordered and mutable. Sets are created
using curly braces {} or the set() function.
Example:
my_set = {1, 2, 3}
print(my_set)
Advantages:
Contains unique elements only, eliminating duplicates.
Fast membership testing and operations like intersection and union.
Disadvantages:
Not ordered – Elements are not stored in a specific order.
Use Cases and Applications:
Removing duplicates from a list.
Checking for membership or common elements between sets.
Dictionary
You create dictionaries in Python using curly braces {} and colons : to define key-value pairs.
They let you store unordered and mutable collections of data.
Example:
my_dict = {'key1': 'value1', 'key2': 2}
print(my_dict)
Advantages:
Fast lookups based on keys.
Key-value pair structure allows for easy data retrieval.
Disadvantages:
Not ordered – No guarantee on the order of key-value pairs.
Use Cases and Applications:
Storing data with a key for easy retrieval.
Mapping unique identifiers to values for quick access.
Practical Implementation
Lists in Python
Lists are versatile data structures in Python that can hold heterogeneous elements.
Practical Implementation Example:
Let’s create a list of fruits and print each fruit:
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
print(fruit)
Best Practices and Optimization Tips:
Use list comprehension for concise and efficient code:
numbers = [1, 2, 3]
for num in numbers[:]:
numbers.append(num * 2)
Tuples in Python
Tuples are immutable sequences in Python, typically used to represent fixed collections of items.
Practical Implementation Example:
Creating a tuple of coordinates:
point = (3, 4)
distances = {(0, 0): 0, (1, 1): 1}
distance_to_origin = distances.get(point, -1)
Common Pitfalls and Solutions:
Attempting to modify a tuple will result in an error. If mutability is required, consider using a list.
Sets in Python
Use sets in Python when you need to store unique elements, test for membership, or eliminate
duplicates without caring about order.
Practical Implementation Example:
Creating a set of unique letters in a word:
word = 'hello'
unique_letters = set(word)
print(unique_letters)
Best Practices and Optimization Tips:
Use set operations like intersection, union, and difference for efficient manipulation of data:
set1 = {1, 2, 3}
set2 = {3, 4, 5}
intersection = set1 & set2
Common Pitfalls and Solutions:
Accidentally mutating a set during iteration can lead to unexpected behavior. To prevent this,
operate on a copy of the set.
Dictionaries in Python
Dictionaries are key-value pairs that allow for fast lookups and mappings between items.
Practical Implementation Example:
Creating a dictionary of phone contacts:
Array
An array is defined as a container that stores the collection of items at contiguous memory locations.
The array is an idea of storing multiple items of the same type together and it makes it easier to
calculate the position of each element. It is used to store multiple values in a single variable.
Creating an Array
For creating an array in Python, we need to import the array module.
After importing, the array module we just have to use the array function which is used to create the
arrays in Python.
Syntax
print(myArr)
Explanation
Adding Element to Array
As we all know, arrays are mutable in nature. So we can add an element to the existing array.
We can use 2 different methods to add the elements to the existing array. These methods are:
.append(): This is used to add a single element to the existing array. By using the append
method the element gets added at the end of the existing array.
.extend(): This is used to add an array to the existing array. By using the extend method the
array that we have added to the extend function gets merged at the end of the existing array.
And, finally, we got the updated array where we have the combination of the original and the
new array.
Let's checkout with the help of an example of how these functions are used to add elements at the
end of the array.
Syntax
indOfElement = 2
accessedElement = myArr[indOfElement]