Learn Python Coding
Learn Python through simple, practical examples and real coding ideas. Clear explanations, useful snippets, and hands-on learning for anyone starting or improving their programming skills. Admin: @HusseinSheikho || @Hussein_Sheikho
Mostrar más📈 Análisis del canal de Telegram Learn Python Coding
El canal Learn Python Coding (@pythonre) en el segmento lingüístico de Inglés es un actor destacado. Actualmente la comunidad reúne a 39 155 suscriptores, ocupando la posición 3 508 en la categoría Tecnologías y Aplicaciones y el puesto 10 563 en la región India.
📊 Métricas de audiencia y dinámica
Desde su creación el невідомо, el proyecto ha mostrado un crecimiento acelerado, reuniendo a 39 155 suscriptores.
Según los últimos datos del 08 junio, 2026, el canal mantiene una actividad estable. En los últimos 30 días la variación de miembros fue de 425, y en las últimas 24 horas de 11, conservando un alto alcance.
- Estado de verificación: No verificado
- Tasa de interacción (ER): El promedio de interacción de la audiencia es 2.56%. Durante las primeras 24 horas tras publicar, el contenido suele obtener 1.00% de reacciones respecto al total de suscriptores.
- Alcance de las publicaciones: Cada publicación recibe en promedio 1 003 visualizaciones. En el primer día suele acumular 391 visualizaciones.
- Reacciones e interacción: La audiencia responde de forma activa: el promedio de reacciones por publicación es 4.
- Intereses temáticos: El contenido se centra en temas clave como math, harvard, oxford, supervision, waybienad.
📝 Descripción y política de contenido
El autor describe el recurso como un espacio para expresar opiniones subjetivas:
“Learn Python through simple, practical examples and real coding ideas. Clear explanations, useful snippets, and hands-on learning for anyone starting or improving their programming skills.
Admin: @HusseinSheikho || @Hussein_Sheikho”
Gracias a la alta frecuencia de actualizaciones (últimos datos recibidos el 09 junio, 2026), el canal mantiene la vigencia y un amplio alcance. La analítica demuestra que la audiencia interactúa activamente con el contenido, lo que lo convierte en un punto de referencia dentro de la categoría Tecnologías y Aplicaciones.
def filter_even_numbers(numbers):
return [num for num in numbers if num % 2 == 0]
my_numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(filter_even_numbers(my_numbers))
[2, 4, 6, 8, 10]#97. Explain what
* does when unpacking a list or tuple.
A: The * operator can be used to unpack an iterable into individual elements. It's often used for function arguments or in assignments.
numbers = [1, 2, 3, 4, 5]
first, *middle, last = numbers
print(f"First: {first}")
print(f"Middle: {middle}")
print(f"Last: {last}")
First: 1 Middle: [2, 3, 4] Last: 5#98. Write a function to merge two sorted lists into a single sorted list. A: You can simply concatenate them and sort, but a more efficient approach (O(n+m)) is to iterate through both lists simultaneously.
def merge_sorted_lists(list1, list2):
# The simple, Pythonic way
return sorted(list1 + list2)
l1 = [1, 3, 5]
l2 = [2, 4, 6]
print(merge_sorted_lists(l1, l2))
[1, 2, 3, 4, 5, 6]#99. What will be the output of the following code? A: This question tests understanding of mutable default arguments.
def my_func(item, my_list=[]):
my_list.append(item)
return my_list
print(my_func(1))
print(my_func(2))
print(my_func(3))
[1] [1, 2] [1, 2, 3]The default list is created only once when the function is defined. It is then shared across all subsequent calls, leading to this surprising behavior. The correct way is to use
my_list=None as the default.
#100. How would you count the occurrences of each word in a given text sentence?
A: The collections.Counter is the ideal tool for this task.
from collections import Counter
import re
sentence = "The quick brown fox jumps over the lazy dog dog"
# Pre-process: lowercase and split into words
words = re.findall(r'\w+', sentence.lower())
word_counts = Counter(words)
print(word_counts)
Counter({'the': 2, 'dog': 2, 'quick': 1, 'brown': 1, 'fox': 1, 'jumps': 1, 'over': 1, 'lazy': 1})
━━━━━━━━━━━━━━━
By: @DataScience4 ✨def fibonacci_generator(n):
a, b = 0, 1
count = 0
while count < n:
yield a
a, b = b, a + b
count += 1
for num in fibonacci_generator(10):
print(num, end=' ')
0 1 1 2 3 5 8 13 21 34#88. Solve the FizzBuzz problem. A: Print numbers from 1 to n. But for multiples of three, print "Fizz" instead of the number, and for the multiples of five, print "Buzz". For numbers which are multiples of both three and five, print "FizzBuzz".
def fizzbuzz(n):
for i in range(1, n + 1):
if i % 3 == 0 and i % 5 == 0:
print("FizzBuzz")
elif i % 3 == 0:
print("Fizz")
elif i % 5 == 0:
print("Buzz")
else:
print(i)
fizzbuzz(15)
#89. Find the factorial of a number using recursion.
A: The factorial of n is the product of all positive integers up to n.
def factorial(n):
if n < 0:
return "Factorial does not exist for negative numbers"
elif n == 0:
return 1
else:
return n * factorial(n - 1)
print(factorial(5))
120#90. Reverse a string in Python. A: The simplest and most Pythonic way is to use slicing.
my_string = "hello"
reversed_string = my_string[::-1]
print(reversed_string)
olleh--- #91. Find the most frequent element in a list. A: The
collections.Counter class is perfect for this.
from collections import Counter
my_list = [1, 2, 3, 2, 4, 2, 5, 2]
count = Counter(my_list)
most_common_element = count.most_common(1)[0][0]
print(most_common_element)
2#92. Check if two strings are anagrams. A: Anagrams are words formed by rearranging the letters of another. If the sorted versions of the two strings are equal, they are anagrams.
def are_anagrams(s1, s2):
return sorted(s1) == sorted(s2)
print(are_anagrams("listen", "silent"))
print(are_anagrams("hello", "world"))
True False#93. Flatten a nested list. A: This can be solved with recursion.
def flatten(nested_list):
flat_list = []
for item in nested_list:
if isinstance(item, list):
flat_list.extend(flatten(item))
else:
flat_list.append(item)
return flat_list
nested = [1, [2, 3], 4, [5, [6, 7]]]
print(flatten(nested))
[1, 2, 3, 4, 5, 6, 7]#94. Find all pairs of an integer array whose sum is equal to a given number. A: A hash set (or a dictionary) can be used to solve this in O(n) time.
def find_sum_pairs(arr, target_sum):
seen = set()
pairs = []
for num in arr:
complement = target_sum - num
if complement in seen:
pairs.append((complement, num))
seen.add(num)
return pairs
my_array = [2, 7, 4, 1, 5, 6]
print(find_sum_pairs(my_array, 8))
[(1, 7), (2, 6)]#95. Write a simple decorator that logs the execution time of a function. A: Use the
time module and wrap the function call.
import time
def timer_decorator(func):
def wrapper(*args, **kwargs):
start_time = time.time()
result = func(*args, **kwargs)
end_time = time.time()
print(f"Function {func.__name__} took {end_time - start_time:.4f} seconds to run.")
return result
return wrapper
@timer_decorator
def long_running_function():
time.sleep(1)
long_running_function()
Function long_running_function took 1.0010 seconds to run.--- #96. Write a function that takes a list of numbers and returns a new list containing only the even numbers. A: List comprehension is a great way to do this.
for loop work internally?
A: The for loop in Python works with the iterator protocol. When you write for item in iterable:, Python first calls iter(iterable) to get an iterator object. Then, it repeatedly calls next() on this iterator object and assigns the result to item until a StopIteration exception is raised, which signals the end of the loop.
#79. What is the requests library used for?
A: The requests library is the de-facto standard for making HTTP requests in Python. It simplifies the process of interacting with web services and APIs.
import requests
response = requests.get('https://api.github.com')
print(response.status_code)
200#80. How do you work with JSON files in Python? A: Use the built-in
json module.
• json.dump() / json.dumps(): To serialize a Python object into a JSON formatted stream or string.
• json.load() / json.loads(): To de-serialize a JSON formatted stream or string into a Python object.
import json
data = {'name': 'John', 'age': 30}
json_string = json.dumps(data)
print(json_string)
{"name": "John", "age": 30}
---
#81. What is the os module used for?
A: The os module provides a way of using operating system-dependent functionality like reading or writing to the file system, interacting with environment variables, and managing directories.
#82. What is monkey-patching?
A: Monkey-patching is a technique used to dynamically modify or extend code at runtime. For example, you can change the behavior of a function or a method in a third-party library without altering the original source code.
#83. What is a metaclass?
A: A metaclass is a "class of a class". It defines how a class behaves. A class is an instance of a metaclass. In Python, type is the default metaclass. It's an advanced concept used for creating custom class behaviors.
#84. What is the difference between range() and xrange()?
A: This is a Python 2 question.
• In Python 2, range() created an actual list in memory, which was inefficient for very large ranges. xrange() created a generator-like object that yielded numbers on demand.
• In Python 3, the old range() was removed, and xrange() was renamed to range(). So, Python 3's range() behaves like Python 2's memory-efficient xrange().
#85. What are some popular Python frameworks for web development?
A:
• Django: A high-level, "batteries-included" framework that encourages rapid development and clean, pragmatic design.
• Flask: A lightweight microframework that is simpler and more flexible, allowing developers to choose their own libraries and tools.
• FastAPI: A modern, high-performance web framework for building APIs with Python 3.7+ based on standard Python type hints.
---
Part 6: Coding Problems & Algorithms (Q86-100)
#86. Write a function to check if a string is a palindrome.
A: A palindrome reads the same forwards and backward. The easiest way is to compare the string with its reversed version.
def is_palindrome(s):
# Clean the string (optional, depends on requirements)
s = ''.join(filter(str.isalnum, s)).lower()
return s == s[::-1]
print(is_palindrome("A man, a plan, a canal: Panama"))
print(is_palindrome("racecar"))
print(is_palindrome("hello"))
True True False#87. Write a Fibonacci sequence generator. A: A generator is memory-efficient for this task.
+, -, *) for your custom classes. This is done by implementing the corresponding magic methods (e.g., __add__ for +, __mul__ for *).
---
Part 5: Advanced Concepts & Libraries (Q71-85)
#71. Explain exception handling in Python.
A: Exception handling is a mechanism for responding to runtime errors.
• try: The block of code to be attempted, which may cause an error.
• except: This block is executed if an error occurs in the try block. You can specify the type of exception to catch.
• else: This block is executed if no exceptions are raised in the try block.
• finally: This block is always executed, whether an exception occurred or not. It's often used for cleanup operations.
try:
result = 10 / 2
except ZeroDivisionError:
print("Cannot divide by zero!")
else:
print(f"Result is {result}")
finally:
print("Execution finished.")
Result is 5.0 Execution finished.#72. How do you raise a custom exception? A: You can define a custom exception by creating a new class that inherits from the built-in
Exception class. Then, use the raise keyword to throw it.
class MyCustomError(Exception):
pass
raise MyCustomError("Something went wrong!")
#73. What is the purpose of the with statement?
A: The with statement simplifies exception handling by encapsulating common try...finally cleanup patterns. It is used with objects that support the context management protocol (which have __enter__ and __exit__ methods). It's most commonly used for managing file streams, ensuring the file is closed automatically.
# The file is automatically closed after this block
with open('file.txt', 'w') as f:
f.write('hello')
#74. What is the difference between multithreading and multiprocessing?
A:
• Multithreading: Multiple threads run within the same process, sharing the same memory space. Due to the GIL, it's best for I/O-bound tasks (like network requests or file operations) where threads can wait without blocking the entire program.
• Multiprocessing: Multiple processes run, each with its own memory space and Python interpreter. This allows for true parallelism and is ideal for CPU-bound tasks (like heavy calculations) as it bypasses the GIL.
#75. What is the difference between a module and a package?
A:
• Module: A single Python file (.py) containing statements and definitions.
• Package: A way of organizing related modules into a directory hierarchy. A directory must contain a file named __init__.py (which can be empty) to be considered a package.
---
#76. What are virtual environments? Why are they important?
A: A virtual environment is an isolated Python environment that allows you to manage dependencies for a specific project separately. They are important because they prevent package version conflicts between different projects on the same machine.
#77. What is pip?
A: pip is the standard package manager for Python. It allows you to install and manage third-party libraries and packages from the Python Package Index (PyPI).ClassName.mro().
#63. What is polymorphism?
A: Polymorphism means "many forms". In programming, it refers to methods/functions/operators with the same name that can be executed on many objects or classes.
class Cat:
def speak(self):
return "Meow"
class Dog:
def speak(self):
return "Woof"
def make_sound(animal):
print(animal.speak())
make_sound(Cat())
make_sound(Dog())
Meow Woof#64. What is the difference between a class method and a static method? A: • Instance Method: Takes
self as the first argument. It can access and modify instance attributes.
• @classmethod: Takes cls (the class itself) as the first argument. It can access and modify class attributes but not instance attributes. Often used as alternative constructors.
• @staticmethod: Does not take self or cls as an implicit first argument. It's essentially a regular function namespaced within the class. It cannot access or modify class or instance state.
#65. What is super()?
A: super() is a built-in function that returns a proxy object that allows you to refer to the parent class. It's commonly used in __init__ methods of child classes to call the parent class's __init__ method, ensuring that parent initializations are not missed.
class Parent:
def __init__(self):
print("Parent init")
class Child(Parent):
def __init__(self):
super().__init__() # Call the Parent's init method
print("Child init")
c = Child()
Parent init Child init--- #66. What are public, protected, and private members? A: These are conventions for encapsulation. • Public: Accessible from anywhere. (e.g.,
member)
• Protected: Conventionally treated as non-public; accessible within the class and its subclasses. Denoted by a single underscore prefix. (e.g., _member)
• Private: Accessible only from within the class. Python enforces this through name mangling. Denoted by a double underscore prefix. (e.g., __member)
#67. What is name mangling?
A: When an identifier starts with two underscores (like __spam), it is textually replaced with _classname__spam. This is done to avoid naming conflicts with subclasses.
#68. What are magic methods (or dunder methods)?
A: Magic methods are special methods with double underscores at the beginning and end of their names (e.g., __init__, __len__, __str__). They are not meant to be called directly but are invoked internally by Python in response to certain operations. For example, len(my_object) calls my_object.__len__().
#69. Explain the difference between __str__ and __repr__.
A:
• __str__(): Called by str(object) and print(object). It should return a user-friendly, readable string representation of the object.
• __repr__(): Called by repr(object). It should return an unambiguous, official string representation of the object, which can ideally be used to recreate the object (e.g., eval(repr(object)) == object). If __str__ is not defined, __repr__ is used as a fallback.object.method()) and can access and modify the object's data (its attributes).
• A function is not associated with any object. It is called by its name (function()).
#54. What does the nonlocal keyword do?
A: The nonlocal keyword is used in nested functions to refer to a variable in the nearest enclosing scope (but not the global scope). It's used to modify variables in an outer (but not global) function.
def outer():
x = "local"
def inner():
nonlocal x
x = "nonlocal"
print("inner:", x)
inner()
print("outer:", x)
outer()
inner: nonlocal outer: nonlocal#55. What is a first-class function? A: In Python, functions are "first-class citizens". This means they can be treated like any other object: they can be assigned to variables, stored in data structures (like lists), passed as arguments to other functions, and returned from functions. --- Part 4: Object-Oriented Programming (OOP) (Q56-70) #56. What are the four main principles of OOP? A: • Encapsulation: Bundling data (attributes) and methods that operate on the data into a single unit (a class). • Inheritance: A mechanism where a new class (subclass) inherits attributes and methods from an existing class (superclass). • Polymorphism: The ability of an object to take on many forms. For example, different classes can have methods with the same name that perform different actions. • Abstraction: Hiding complex implementation details and showing only the essential features of the object. #57. What is the difference between a class and an object? A: • A Class is a blueprint or template for creating objects. It defines a set of attributes and methods. • An Object is an instance of a class. It is a concrete entity created from the class blueprint, with actual values for its attributes. #58. What is
self?
A: self represents the instance of the class. By using the self keyword, we can access the attributes and methods of the class in Python. It is the first argument passed to instance methods.
#59. What is the __init__ method?
A: __init__ is a special method in Python classes, also known as the constructor. It is automatically called when a new object of the class is created. It is used to initialize the object's attributes.
class Dog:
def __init__(self, name):
self.name = name # Initialize the name attribute
print(f"{self.name} was born!")
my_dog = Dog("Rex")
Rex was born!#60. What is inheritance? A: Inheritance allows us to define a class that inherits all the methods and properties from another class. The parent class is the class being inherited from, and the child class is the class that inherits.
class Animal:
def speak(self):
print("Animal speaks")
class Dog(Animal): # Dog inherits from Animal
def bark(self):
print("Woof!")
d = Dog()
d.speak() # Inherited from Animal
d.bark()
Animal speaks Woof!--- #61. What is multiple inheritance? A: Multiple inheritance is a feature where a class can inherit attributes and methods from more than one parent class. Python supports multiple inheritance.
class A:
def method(self):
print("Method from A")
class B:
def method(self):
print("Method from B")
class C(B, A): # Inherits from B, then A
pass
c = C()
c.method() # Calls method from B due to MRO
Method from B
def count_up_to(max):
count = 1
while count <= max:
yield count
count += 1
counter = count_up_to(3)
print(next(counter))
print(next(counter))
print(next(counter))
1 2 3#45. What is the difference between an iterator and a generator? A: • Iterator: An object that implements the iterator protocol (
__iter__() and __next__() methods). It's more complex to create as you have to write a class.
• Generator: A simpler way to create an iterator using a function with the yield keyword. All generators are iterators, but not all iterators are generators.
---
#46. Explain the map() function.
A: The map(function, iterable) function applies the given function to every item of the iterable and returns a map object (an iterator) with the results.
numbers = [1, 2, 3, 4]
squared_numbers = map(lambda x: x**2, numbers)
print(list(squared_numbers))
[1, 4, 9, 16]#47. Explain the
filter() function.
A: The filter(function, iterable) function constructs an iterator from elements of the iterable for which the function returns True.
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = filter(lambda x: x % 2 == 0, numbers)
print(list(even_numbers))
[2, 4, 6]#48. What does the
global keyword do?
A: The global keyword is used to modify a global variable from inside a function. Without it, assigning a value to a variable inside a function creates a new local variable.
count = 0
def increment():
global count
count += 1
increment()
print(count)
1#49. Can a function return multiple values? A: Yes. A Python function can return multiple values by separating them with commas. Internally, Python packs these values into a single tuple and returns that tuple.
def get_name_and_age():
return "Alice", 25
name, age = get_name_and_age()
print(f"Name: {name}, Age: {age}")
Name: Alice, Age: 25#50. What are docstrings? A: A docstring is a string literal that occurs as the first statement in a module, function, class, or method definition. It is used to document what the code does. It is accessible via the
__doc__ attribute.
def add(a, b):
"""This function adds two numbers and returns the result."""
return a + b
print(add.__doc__)
This function adds two numbers and returns the result.--- #51. What are closures in Python? A: A closure is a function object that remembers values in the enclosing scope even if they are not present in memory. It's a function that is defined inside another function (the enclosing function) and references variables from that enclosing function.
def outer_function(text):
def inner_function():
print(text) # inner_function "closes over" the text variable
return inner_function
my_func = outer_function("Hello")
my_func()
Hello#52. What is recursion? Provide a simple example. A: Recursion is a programming technique where a function calls itself in order to solve a problem. A recursive function must have a base case that stops the recursion.
# Calculate factorial using recursion
def factorial(n):
if n == 1:
return 1 # Base case
else:
return n * factorial(n - 1) # Recursive call
print(factorial(5))
120
KeyError?
A: Use the .get(key, default_value) method. It returns the value for the key if it exists, otherwise it returns the default_value (which is None if not specified).
my_dict = {'a': 1}
print(my_dict.get('a'))
print(my_dict.get('b', 'Not Found'))
1 Not Found#38. What is a hashable object? A: An object is hashable if it has a hash value that never changes during its lifetime. This means it must be immutable. Hashable objects can be used as dictionary keys and set members. Examples:
int, str, tuple.
#39. What is dictionary comprehension?
A: It is a concise and readable way to create a dictionary.
# Create a dictionary of numbers and their squares
squares_dict = {x: x**2 for x in range(5)}
print(squares_dict)
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
#40. Explain how to use zip() to combine two lists.
A: The zip() function takes two or more iterables and returns an iterator of tuples, where the i-th tuple contains the i-th element from each of the argument iterables. It stops when the shortest input iterable is exhausted.
names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]
combined = list(zip(names, ages))
print(combined)
[('Alice', 25), ('Bob', 30), ('Charlie', 35)]
---
Part 3: Functions & Functional Programming (Q41-55)
#41. What are *args and **kwargs?
A: They are used to pass a variable number of arguments to a function.
• *args (Non-Keyword Arguments): Gathers extra positional arguments into a tuple.
• **kwargs (Keyword Arguments): Gathers extra keyword arguments into a dictionary.
def my_func(a, b, *args, **kwargs):
print(f"a: {a}, b: {b}")
print(f"args: {args}")
print(f"kwargs: {kwargs}")
my_func(1, 2, 3, 4, name="Alice", city="NY")
a: 1, b: 2
args: (3, 4)
kwargs: {'name': 'Alice', 'city': 'NY'}
#42. What is a lambda function?
A: A lambda function is a small, anonymous function defined with the lambda keyword. It can take any number of arguments but can only have one expression. They are often used when a simple function is needed for a short period.
# A lambda function that doubles its input
double = lambda x: x * 2
print(double(5))
10#43. What is a decorator? A: A decorator is a design pattern in Python that allows a user to add new functionality to an existing object (like a function) without modifying its structure. Decorators are usually called before the definition of a function you want to decorate.
def my_decorator(func):
def wrapper():
print("Something is happening before the function is called.")
func()
print("Something is happening after the function is called.")
return wrapper
@my_decorator
def say_hello():
print("Hello!")
say_hello()
Something is happening before the function is called. Hello! Something is happening after the function is called.#44. What is a generator? What is the
yield keyword?
A: A generator is a special type of iterator that is simpler to create. Instead of returning a value and terminating, a generator function uses the yield keyword. When yield is called, it "pauses" the function, returns the value, and saves its state. On the next call, it resumes execution from where it left off. Generators are memory efficient for working with large data sequences.| (union) operator. For earlier versions, you can use the ** unpacking operator or the .update() method.
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
# Using the | operator (Python 3.9+)
merged_dict = dict1 | dict2
print(merged_dict)
{'a': 1, 'b': 3, 'c': 4}
#28. How do you iterate over the keys, values, and items of a dictionary?
A: Use the .keys(), .values(), and .items() methods.
my_dict = {'name': 'Alice', 'age': 25}
for key, value in my_dict.items():
print(f"{key}: {value}")
name: Alice age: 25#29. What is a set? What are its main properties? A: A set is an unordered collection of unique elements. • Unique: Sets cannot have duplicate members. • Unordered: The elements are not stored in any specific order. • Mutable: You can add or remove elements from a set. #30. What is a
frozenset?
A: A frozenset is an immutable version of a set. Once created, you cannot add or remove elements. Because they are immutable and hashable, they can be used as dictionary keys or as elements of another set.
---
#31. How do you find the intersection of two sets?
A: Use the & operator or the .intersection() method.
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
print(set1 & set2)
{3, 4}
#32. What is the difference between .append() and .extend() for lists?
A:
• .append(element): Adds its argument as a single element to the end of a list.
• .extend(iterable): Iterates over its argument and adds each element to the list, extending the list.
list_a = [1, 2, 3]
list_b = [1, 2, 3]
list_a.append([4, 5])
list_b.extend([4, 5])
print(f"After append: {list_a}")
print(f"After extend: {list_b}")
After append: [1, 2, 3, [4, 5]] After extend: [1, 2, 3, 4, 5]#33. How do you reverse a list? A: • Use the
.reverse() method to reverse the list in-place.
• Use slicing [::-1] to create a new, reversed copy of the list.
my_list = [1, 2, 3, 4]
reversed_copy = my_list[::-1]
print(reversed_copy)
[4, 3, 2, 1]#34. What is
defaultdict?
A: defaultdict is a subclass of the standard dict that is found in the collections module. It overrides one method and adds one writable instance variable. Its main advantage is that it does not raise a KeyError if you try to access a key that does not exist. Instead, it provides a default value for that key.
from collections import defaultdict
d = defaultdict(int) # Default value for non-existent keys will be int(), which is 0
d['a'] += 1
print(d['a'])
print(d['b']) # Accessing a non-existent key
1 0#35. What is the time complexity of a key lookup in a list vs. a dictionary? A: • List: O(n), because in the worst case, you may have to scan the entire list to find an element. • Dictionary/Set: O(1) on average. Dictionaries use a hash table, which allows for direct lookup of a key's location without scanning. #36. How do you create an empty set? A: You must use the
set() constructor. Using {} creates an empty dictionary, not an empty set.
empty_dict = {}
empty_set = set()
print(type(empty_dict))
print(type(empty_set))
<class 'dict'>
<class 'set'>int(), float(), str(), and list() are used for this.
string_num = "123"
integer_num = int(string_num)
print(integer_num + 7)
130#19. What are Python literals? A: A literal is a notation for representing a fixed value in source code. Examples include: • String literals:
"hello", 'world'
• Numeric literals: 100, 3.14
• Boolean literals: True, False
• Special literal: None
#20. How do you create a multi-line string?
A: Use triple quotes, either """ or '''.
multi_line = """This is a string
that spans across
multiple lines."""
print(multi_line)
This is a string that spans across multiple lines.--- Part 2: Data Structures (Q21-40) #21. What is the main difference between a List and a Tuple? A: The primary difference is that Lists are mutable, meaning their elements can be changed, added, or removed. Tuples are immutable, meaning once they are created, their elements cannot be changed. Tuples are generally faster than lists. #22. What are list comprehensions? Provide an example. A: A list comprehension is a concise and readable way to create a list. It consists of brackets containing an expression followed by a
for clause, then zero or more for or if clauses.
# Create a list of squares for numbers 0 through 9
squares = [x**2 for x in range(10)]
print(squares)
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]#23. How do you remove duplicates from a list? A: The simplest way is to convert the list to a set and then back to a list. Sets automatically discard duplicate elements. This method does not preserve the original order.
my_list = [1, 2, 3, 2, 4, 1, 5]
unique_list = list(set(my_list))
print(unique_list)
[1, 2, 3, 4, 5]#24. What is the difference between
.sort() and sorted()?
A:
• .sort() is a list method that sorts the list in-place (modifies the original list) and returns None.
• sorted() is a built-in function that takes an iterable as an argument and returns a new sorted list, leaving the original iterable unchanged.
my_list = [3, 1, 2]
sorted_list = sorted(my_list)
print(f"Original list after sorted(): {my_list}")
print(f"New list from sorted(): {sorted_list}")
my_list.sort()
print(f"Original list after .sort(): {my_list}")
Original list after sorted(): [3, 1, 2] New list from sorted(): [1, 2, 3] Original list after .sort(): [1, 2, 3]#25. Explain slicing in Python. A: Slicing is a feature that allows you to access a range of elements from a sequence (like a list, string, or tuple). The syntax is
sequence[start:stop:step].
• start: The index of the first element to include.
• stop: The index of the first element to exclude.
• step: The amount to increment by.
my_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# Elements from index 2 up to (not including) 5
print(my_list[2:5])
# Every second element
print(my_list[::2])
# Reverse the list
print(my_list[::-1])
[2, 3, 4] [0, 2, 4, 6, 8] [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]--- #26. Can a dictionary key be a list? Why or why not? A: No. Dictionary keys must be of an immutable type. Since lists are mutable, they cannot be used as dictionary keys. You can use immutable types like strings, numbers, or tuples as keys.
print, len). This is known as the LEGB rule.
---
#11. What is the ternary operator in Python?
A: It's a concise way to write a simple if-else statement in a single line. The syntax is [value_if_true] if [condition] else [value_if_false].
age = 20
status = "Adult" if age >= 18 else "Minor"
print(status)
Adult#12. What are negative indexes? A: Negative indexes are used to access elements from the end of a sequence (like a list or string).
-1 refers to the last element, -2 to the second-to-last, and so on.
my_list = ['a', 'b', 'c', 'd']
print(my_list[-1])
print(my_list[-2])
d c#13. What is pickling and unpickling? A: Pickling is the process of converting a Python object hierarchy into a byte stream (serialization). Unpickling is the inverse operation, converting a byte stream back into an object hierarchy (deserialization). The
pickle module is used for this.
import pickle
my_dict = {'name': 'Alice'}
# Pickling
with open('data.pkl', 'wb') as f:
pickle.dump(my_dict, f)
# Unpickling
with open('data.pkl', 'rb') as f:
loaded_dict = pickle.load(f)
print(loaded_dict)
{'name': 'Alice'}
#14. How do you copy an object in Python?
A:
• Shallow Copy: Creates a new object but inserts references to the objects found in the original.
• Deep Copy: Creates a new object and recursively copies all objects found in the original. Changes to the copied object will not affect the original. Use the copy module.
import copy
original_list = [[1, 2], [3, 4]]
shallow = copy.copy(original_list)
deep = copy.deepcopy(original_list)
# Modify a nested object
shallow[0][0] = 99
print(f"Original: {original_list}") # Modified!
print(f"Shallow Copy: {shallow}")
print(f"Deep Copy: {deep}") # Not modified
Original: [[99, 2], [3, 4]] Shallow Copy: [[99, 2], [3, 4]] Deep Copy: [[1, 2], [3, 4]]#15. What does the
pass statement do?
A: pass is a null statement. It's used as a placeholder where a statement is syntactically required but you don't want any code to execute. It's often used in empty functions or classes.
def my_empty_function():
pass # No error, does nothing
my_empty_function()
print("Function executed.")
Function executed.--- #16. What does
if __name__ == "__main__:" mean?
A: This is a common idiom in Python. The code inside this block will only run when the script is executed directly (not when it is imported as a module into another script). It's the entry point of the program.
#17. How do you concatenate strings in Python?
A:
• Use the + operator for simple cases.
• Use an f-string (formatted string literal) for embedding expressions (most readable).
• Use the .join() method for concatenating a list of strings (most efficient).
words = ["Python", "is", "awesome"]
sentence = " ".join(words)
print(sentence)
Python is awesome
print: In Python 2, print is a statement (print "hello"). In Python 3, it's a function (print("hello")).
• Integer Division: In Python 2, 5 / 2 results in 2 (floor division). In Python 3, it results in 2.5 (true division).
• Unicode: In Python 3, strings are Unicode (UTF-8) by default. In Python 2, you had to explicitly use u"unicode string".
#4. What are mutable and immutable data types in Python?
A:
• Mutable: Objects whose state or contents can be changed after creation. Examples: list, dict, set.
• Immutable: Objects whose state cannot be changed after creation. Examples: int, float, str, tuple, frozenset.
# Mutable example
my_list = [1, 2, 3]
my_list[0] = 99
print(my_list)
[99, 2, 3]#5. How is memory managed in Python? A: Python uses a private heap to manage memory. A built-in garbage collector automatically reclaims memory from objects that are no longer in use. The primary mechanism is reference counting, where each object tracks the number of references to it. When the count drops to zero, the object is deallocated. #6. What is the difference between
is and ==?
A:
• == (Equality): Checks if the values of two operands are equal.
• is (Identity): Checks if two variables point to the exact same object in memory.
list_a = [1, 2, 3]
list_b = [1, 2, 3]
list_c = list_a
print(list_a == list_b) # True, values are the same
print(list_a is list_b) # False, different objects in memory
print(list_a is list_c) # True, same object in memory
True False True#7. What is PEP 8? A: PEP 8 (Python Enhancement Proposal 8) is the official style guide for Python code. It provides conventions for writing readable and consistent Python code, covering aspects like naming conventions, code layout, and comments. #8. What is the difference between a
.py and a .pyc file?
A:
• .py: This is the source code file you write.
• .pyc: This is the compiled bytecode. When you run a Python script, the interpreter compiles it into bytecode (a lower-level, platform-independent representation) and saves it as a .pyc file to speed up subsequent executions.
#9. What are namespaces in Python?
A: A namespace is a system that ensures all names in a program are unique and can be used without conflict. It's a mapping from names to objects. Python has different namespaces: built-in, global, and local.
¡Ya disponible! Investigación de Telegram 2025 — los principales insights del año 
