Basic NumPy for beginners:
Creating a NumPy array: To create a NumPy array from a list or tuple, you can use the np.array() function. For example, the following code creates a NumPy array from a list of numbers:
import numpy as npoutput:
# Create a NumPy array from a list of numbers
numbers = [1, 2, 3, 4, 5]
numbers_array = np.array(numbers)
# Print the array
print(numbers_array)
import numpy as npoutput:
# Create two NumPy arrays
x = np.array([1, 2, 3, 4, 5])
y = np.array([6, 7, 8, 9, 10])
# Add the arrays element-wise
z = x + y
# Print the result
print(z)
import numpy as npoutput:
# Create a NumPy array
numbers = np.array([1, 2, 3, 4, 5])
# Slice the array to extract the second and third elements
subarray = numbers[1:3]
# Print the result
print(subarray)
Commonly used Python libraries are:
👉🏻NumPy: This library is used for scientific computing and working with arrays of data. It provides functions for working with arrays of data, including mathematical operations, linear algebra, and random number generation.
👉🏻Pandas: This library is used for data manipulation and analysis. It provides tools for importing, cleaning, and transforming data, as well as tools for working with time series data and performing statistical analysis.
👉🏻Matplotlib: This library is used for data visualization. It provides functions for creating a wide range of plots, including scatter plots, line plots, bar plots, and histograms.
👉🏻Scikit-learn: This library is used for machine learning. It provides a range of algorithms for classification, regression, clustering, and dimensionality reduction, as well as tools for model evaluation and selection.
👉🏻TensorFlow: This library is used for deep learning. It provides a range of tools and libraries for building and training neural networks, including support for distributed training and hardware acceleration.
Share and Support
@Python_Codes
Common techniques for using the repr() function in Python:
Get the string representation of an object:
my_object = "Hello, world!"Print the string representation of an object:
my_repr = repr(my_object)
Use the string representation of an object for debugging:
my_object = "Hello, world!"
print(repr(my_object))
Use the string representation of an object as a dictionary key:
my_object = "Hello, world!"
print(f"my_object: {repr(my_object)}")
Use the string representation of an object as a set element:
my_object = "Hello, world!"
my_repr = repr(my_object)
my_dict = {}
my_dict[my_repr] = my_object
my_object = "Hello, world!"Keep in mind that the repr() function is used to generate a string representation of an object that is meant to be readable and unambiguous. The resulting string may not be the same as the original value of the object, and it may not be suitable for use in some contexts.
my_repr = repr(my_object)
my_set = set()
my_set.add(my_repr)
The union of two sets can be found using the union() method.
Here is an example:
set1 = {1, 2, 3}This will create a new set called union_set that contains all of the items from set1 and set2. In this case, union_set will be equal to {1, 2, 3, 4, 5}.
set2 = {3, 4, 5}
union_set = set1.union(set2)
set1 = {1, 2, 3}This will produce the same result as the union() method.
set2 = {3, 4, 5}
union_set = set1 | set2
Common techniques for using the set() function in Python:
1. Create a set from a list:
my_list = [1, 2, 2, 3, 3, 3]2.Add an item to a set:
my_set = set(my_list)
my_set = {1, 2, 3}3.Remove an item from a set by its value:
my_set.add(4)
my_set = {1, 2, 3}4.Check if an item is in a set:
my_set.remove(3)
my_set = {1, 2, 3}5.Get the length of a set:
if 3 in my_set:
print("The item is in the set.")
my_set = {1, 2, 3}6.Loop through the items in a set:
set_length = len(my_set)
my_set = {1, 2, 3}7.Get the union of two sets:
for item in my_set:
print(item)
set1 = {1, 2, 3}8.Get the intersection of two sets:
set2 = {3, 4, 5}
union_set = set1.union(set2)
set1 = {1, 2, 3}Share and Support
set2 = {3, 4, 5}
intersection_set = set1.intersection(set2)
What are pure functions?
A pure function is a function that will return the same value given the same arguments. A function is not pure if there is something outside the function that can change its return value, given the same arguments.
Share and Support
@Python_Codes
How do you check if an array is monotonic?
An array is monotonic if the elements are sorted either in descending order or ascending order.
Share and Support
@Python_Codes
any() function returns True if at least one item is True in the iterable object.
@Python_Codes
Python Tip:
You can use dict on a clas
s instance to get all instance attributes as a dictionary
@Python_Codes
💡 Python Life Hack: Do you know you can copy the files from a computer to a mobile phone 📱 without any cable using Python 🐍 ?
@Python_Codes
NumPy tricks for beginners :
👉 Reshaping arrays: NumPy provides the np.reshape() function, which allows you to change the shape of an array while preserving its data. This can be useful for converting between different data formats, such as converting a one-dimensional array into a two-dimensional matrix. For example, the following code reshapes a one-dimensional array into a two-dimensional matrix with two rows and three columns:
import numpy as npoutput:
# Create a one-dimensional NumPy array
x = np.array([1, 2, 3, 4, 5, 6])
# Reshape the array into a two-dimensional matrix with 2 rows and 3 columns
x_matrix = np.reshape(x, (2, 3))
# Print the resulting matrix
print(x_matrix)
import numpy as npoutput:
# Create two one-dimensional NumPy arrays
x = np.array([1, 2, 3])
y = np.array([4, 5, 6])
# Stack the arrays vertically to create a two-dimensional matrix
z = np.vstack((x, y))
# Print the resulting matrix
print(z)
import numpy as npoutput:
# Create a two-dimensional NumPy array
x = np.array([[1, 2, 3],
[4, 5, 6]])
# Add a scalar value to each element of the array
y = x + 10
# Print the resulting array
print(y)
NumPy is a library for scientific computing in Python. It provides tools for working with arrays of data, including functions for mathematical operations, linear algebra, and random number generation.
👉🏻One of the key features of NumPy is its array data structure, which is similar to a list but allows for more efficient mathematical operations on large datasets. NumPy arrays can be created from existing data, such as lists or tuples, using the np.array() function.
👉🏻Once an array has been created, it can be manipulated using various NumPy functions. For example, the np.mean() function can be used to compute the mean of an array, and the np.random.rand() function can be used to generate random numbers.
👉🏻In addition to its array data structure, NumPy also provides a wide range of mathematical functions for working with arrays, such as linear algebra operations, statistical functions, and trigonometric functions. These functions can be applied to arrays element-wise, allowing for efficient computation on large datasets.
Overall, NumPy is a powerful library for working with arrays of data in Python, and is widely used in the fields of scientific computing, data science, and machine learning.
Share and Support
@Python_Codes
common techniques for using the type() function in Python:
Get the type of an object:
my_object = "Hello, world!"Check if an object is of a given type:
my_type = type(my_object)
my_object = "Hello, world!"Create a new object of a given type:
if type(my_object) == str:
print("my_object is a string.")
my_type = intUse the type of an object as a dictionary key:
my_object = my_type("1")
my_object = "Hello, world!"Use the type of an object as a set element:
my_type = type(my_object)
my_dict = {}
my_dict[my_type] = my_object
my_object = "Hello, world!"The type() function is a built-in function in Python that is used to determine the type of an object. It is a useful tool for checking the type of an object, creating objects of a specific type, and using the type of an object as a key in a dictionary or set.
my_type = type(my_object)
my_set = set()
my_set.add(my_type)
Common techniques for using the hash() function in Python:
Get the hash value of an object:
my_object = "Hello, world!"Hash multiple objects:
my_hash = hash(my_object)
my_object1 = "Hello, world!"Use the hash value for an object as a dictionary key:
my_object2 = (1, 2, 3)
my_object3 = {"key": "value"}
my_hash1 = hash(my_object1)
my_hash2 = hash(my_object2)
my_hash3 = hash(my_object3)
my_object = "Hello, world!"Use the hash value for an object as a set element:
my_hash = hash(my_object)
my_dict = {}
my_dict[my_hash] = my_object
my_object = "Hello, world!"Keep in mind that the hash() function is used to generate a numeric value that represents the value of an object. The value of the hash may change between different runs of a Python program, so it should not be used as a unique identifier for objects unless you are sure that the hash will not change.
my_hash = hash(my_object)
my_set = set()
my_set.add(my_hash)
In general, the Python standard library includes many built-in functions that are available to use in your code without needing to import any additional modules. Some common examples of built-in functions include:
👉🏻 abs() : Returns the absolute value of a number.
👉🏻 all() : Returns True if all elements of an iterable are True, and False otherwise.
👉🏻 any() : Returns True if any element of an iterable is True, and False otherwise.
👉🏻 bin() : Converts an integer to a binary string.
👉🏻 bool() : Converts a value to a Boolean.
👉🏻 chr() : Returns the string representation of a Unicode character.
👉🏻 dir() : Returns a list of attributes and methods for an object.
👉🏻enumerate(): Returns an enumerate object, which contains a sequence of tuples containing the index and value of each element of an iterable.
👉🏻 filter() : Returns an iterator for elements of an iterable for which a condition is True.
👉🏻 float() : Converts a value to a floating-point number.
👉🏻 format(): Formats a string using format specifiers.
👉🏻 hash() : Returns the hash value of an object.
👉🏻 int() : Converts a value to an integer.
👉🏻 isinstance(): Returns True if an object is an instance of a given type, and False otherwise.
👉🏻 len() : Returns the length of an object.
👉🏻 list() : Converts an iterable to a list.
👉🏻 map() : Returns an iterator that applies a function to each element of an iterable.
👉🏻 max() : Returns the maximum value of an iterable.
👉🏻 min() : Returns the minimum value of an iterable.
👉🏻 next() : Returns the next element of an iterator.
👉🏻 open() : Opens a file and returns a file object.
👉🏻 ord() : Returns the Unicode code point for a character.
👉🏻 print() : Prints a message to the standard output.
👉🏻 range() : Returns a sequence of numbers.
👉🏻 repr() : Returns a string representation of an object.
👉🏻 round() : Rounds a number to a specified number of decimal places.
👉🏻 set() : Creates a set object.
👉🏻 sorted() : Returns a sorted list from an iterable.
👉🏻 str() : Converts a value to a string.
👉🏻 sum() : Returns the sum of elements in an iterable.
👉🏻 type() : Returns the type of an object.
👉🏻 zip() : Returns an iterator that combines elements from multiple iterables.
Share and Support
@Python_Codes
Common techniques for using the zip() function in Python:
1. Zip two lists together:
list1 = [1, 2, 3]2. Unzip a zipped list:
list2 = [4, 5, 6]
zipped_lists = zip(list1, list2)
zipped_lists = [(1, 4), (2, 5), (3, 6)]3. Loop through a zipped list:
list1, list2 = zip(*zipped_lists)
zipped_lists = [(1, 4), (2, 5), (3, 6)]4.Convert a zipped list to a dictionary:
for item1, item2 in zipped_lists:
print(item1, item2)
zipped_lists = [(1, 4), (2, 5), (3, 6)]5. Zip three or more lists together:
my_dict = dict(zipped_lists)
list1 = [1, 2, 3]Share and Support
list2 = [4, 5, 6]
list3 = [7, 8, 9]
zipped_lists = zip(list1, list2, list3)
💡🐍 Did you know?
You can use slices in Python to insert elements to a list in arbitrary positions?
Share and Support
@Python_Codes
round() function
the round function is used to convert the floating-point into a specified number of decimals number
@Python_Codes
Most of the time, we don't want to share our wifi passwords, in that case, we generate a QR and stick it on the wall.
@Python_Codes
Use functools.cache to add a simple cache to your Python 🐍 functions.
@Python_Codes
Python Tip:
You can use the calendar module in one line from the command line with python -m calendar
@Python_Codes
Python Class Anatomy
Almost everything a Python class definition can contain summed up in one image :)
@Python_Codes