menu

Search By Label

You should use these comparisons for their semantics.
Use is to check identity and == to check equality.
In Python names refer to objects, for example in this case value1 and value2 refer to an int instance storing the value 1000:

value1 = 1000
value2 = value1
>>> value1 == value2
True
>>> value1 is value2
True
In the following example the names value1 and value2 refer to different int instances, even if both store the same integer. Because the same value (integer) is stored == will be True, that's why it's often called "value comparison". However is will return False because these are different objects:
>>> value1 = 1000
>>> value2 = 1000

>>> value1 == value2 True >>> value1 is value2 False
This will open an interactive help session where you can type in the names of modules, functions, classes, etc., to get information about them.

Example Usage

Here’s a practical example:
import datetime
help(datetime.datetime)
This will provide detailed information about the datetime class within the datetime module, including its methods and usage.
It's a list of public objects of that module, as interpreted by import *. It overrides the default of hiding everything that begins with an underscore.

__all__ in a module, e.g. module.py:

__all__ = ['foo', 'Bar']

means that when you import * from the module, only those names in the __all__ are imported:

from module import *               # imports foo and Bar
Tuples are used to store multiple items in a single variable.

Example:
thistuple = ("apple", "banana", "cherry")
print(thistuple) // ('apple', 'banana', 'cherry')

In Python, arrays and tuples are both used to store collections of data, but they have distinct characteristics and use cases.

A tuple is an ordered and immutable collection of items. Once a tuple is created, its elements cannot be changed. Tuples are defined using parentheses () and can store elements of different data types.
In Python, variables don't directly store values. Instead, they store references to objects in memory. Each object has a reference count, which keeps track of how many variables are pointing to it. When the reference count of an object becomes zero, it's considered garbage and is automatically collected by the garbage collector.
x = 10
y = x
print(id(x))  # Output: 140737469306640
print(id(y))  # Output: 140737469306640
In this example, both x and y refer to the same integer object with the memory address 140737469306640. The reference count of this object is 2.
del x
print(id(y))  # Output: 140737469306640
After deleting x, the reference count of the integer object becomes 1. Since y is still pointing to it, the object is not garbage collected.

Garbage Collection:
Python's garbage collector periodically scans the memory for objects with a reference count of zero. These objects are marked as garbage and are reclaimed by the garbage collector. The exact timing and frequency of garbage collection can vary depending on the Python implementation and workload.
We can delete a property from an object in python with `.pop('property_name', None)` to avoid errors if the object does not exist.
image.png 81.1 KB

Source: https://www.javatpoint.com/difference-between-del-and-pop-in-python#:~:text=In%20Python%2C%20%22del%22%20can,removes%20an%20object%20from%20memory
Within the breakpoint() debugger, type dir(object) to list all available attributes and methods of the object.
This will give you an overview of what you can access.
You can use the method Array.index() to find the position of an element, example:

languages = ["English", "Spanish", "French"]
current_lang = "Spanish"

try:
  # Use the index() method to find the index of the element
  index = languages.index(current_lang)
  print(f"The index of '{current_lang}' in the languages list is: {index}")
except ValueError:
  print(f"'{current_lang}' is not found in the languages list.")

Using json.dumps()
Similar to JavaScript's JSON.stringify(), Python offers json.dumps() to convert a Python object into a JSON string. This is the preferred method for most scenarios as JSON is a widely used and well-structured format.

import json

my_object = {"name": "Alice", "age": 30, "city": "New York"}
json_string = json.dumps(my_object)

print(json_string)  # Output: {"name": "Alice", "age": 30, "city": "New York"}

To specify a Python runtime, add a runtime.txt file to your app’s root directory that declares the exact version number to use.
$ cat runtime.txt
python-3.12.4

Source: https://devcenter.heroku.com/articles/python-runtimes
In Python, if you want to access the index while iterating over a sequence (like a list), you can use the built-in function enumerate().
Here’s how you can do it:
xs = [8, 23, 45]
for index, x in enumerate(xs):
    print(f"item #{index + 1} = {x}")

This will give you the desired output:
item #1 = 8
item #2 = 23
item #3 = 45
Lambda functions are anonymous functions in Python. They allow you to define a small, one-line function without the need for a formal def keyword and a function name.

Example:
Imagine you want to double a number. Here's how you can do it with a regular function:
def double(x):
  """Doubles a number."""
  return x * 2

result = double(5)
print(result)  # Output: 10

This defines a function named double that takes a number (x) as input and returns its double.
Here's how you can achieve the same functionality using a Lambda function:
# Lambda function to double a number
double_lambda = lambda x: x * 2

result = double_lambda(5)
print(result)  # Output: 10

Use Cases:
  • Passing small functions as arguments to other functions.
  • Sorting or filtering data based on a simple criterion.
  • Creating throwaway functions used only once.
The .strip() method in Python is used to remove leading and trailing characters from a string. It's a versatile method with various applications for string manipulation.

Example:
data = "  Hello, world!   "  # String with leading and trailing spaces

stripped_data = data.strip()

print(stripped_data)  # Output: "Hello, world!" (whitespace removed)
Or
data = "**Hello, world!**"  # String with leading and trailing asterisks

stripped_data = data.strip("*")

print(stripped_data)  # Output: "Hello, world!" (asterisks removed)

you can debug any Python app (>3.7 version) by adding the method breakpoint()  to any line.

Here the actions you can use:
h: help
w: where
n: next
s: step (steps into function)
c: continue
p: print
l: list
q: quit

Source: https://www.youtube.com/watch?v=aZJnGOwzHtU&ab_channel=PatrickLoeber
Lambdas in Python are a concise way to define anonymous functions. They are useful for short, inline functions that are used only once or in situations where a full function definition would be cumbersome.

# Syntax
lambda arguments: expression

# Example of use
add = lambda x, y: x + y  # Defines a lambda function that adds two numbers
result = add(5, 3)  # Calls the lambda function with arguments 5 and 3
print(result)  # Output: 8