x = [55, 77, 99, 22, 33]
max_value = x[0]
for i in x:
if i > max_value:
max_value = i
print(max_value)
99
{} Create an empty dictionary: my_dict = {}
dict[key] Access value by key (raises KeyError if not found)
my_dict["name"] → "Alice"
dict.get(key, default) Get value of a key (returns default if key not found)
my_dict.get("age", 30) → 25
dict[key] = value Add or update a key-value pair
my_dict["city"] = "New York"
dict.pop(key, default) Remove key and return value (or default if not found)
my_dict.pop("age") → 25 del dict[key]
Delete a key-value pair
del my_dict["name"]
dict.popitem() Remove and return the last inserted key-value pair
my_dict.popitem() → ("city", "New York")
dict.clear() Remove all elements from the dictionary
my_dict.clear()
dict.keys() Get all keys as a view object
my_dict.keys() → dict_keys(['name', 'age'])
dict.values() Get all values as a view object
my_dict.values() → dict_values(['Alice', 25])
dict.items() Get all key-value pairs as tuples
my_dict.items() → dict_items([('name', 'Alice'), ('age', 25)])
key in dict Check if a key exists in the dictionary
"name" in my_dict → True
key not in dict Check if a key does not exist
"gender" not in my_dict → True
for key in dict: Iterate through keys
for k in my_dict:
print(k, my_dict[k])
for key, value in dict.items():
Iterate through key-value pairs
for k, v in my_dict.items():
print(k, v)
dict.update(other_dict) Merge another dictionary into the current dictionary
my_dict.update({"gender": "Female"})
dict1 = {"name": "Alice", "age": 25, "city": "New York"}
dict1.get("names", "Key not Found")
dict1 = {"name": "Alice", "age": 25, "city": "New York"}
print("name" in dict1)
True
dict1 = {"name": "Alice", "age": 25, "city": "New York"}
removed_name = dict1.pop("name")
removed_name
'Alice'
dict1 = {"name": "Alice", "age": 25, "city": "New York"}
del dict1["name"]
print(dict1)
{'age': 25, 'city': 'New York'}
dict1 = {"name": "Alice", "age": 25, "city": "New York"}
dict1.popitem() # Removes the last element in the dict1.
('city', 'New York')
dict1
{'name': 'Alice', 'age': 25}
dict1.items()
dict_items([('name', 'Alice'), ('age', 25)])
dict1.keys()
dict_keys(['name', 'age'])
dict1.values()
dict_values(['Alice', 25])
dict1["name"] = None
print(dict1)
{'name': None, 'age': 25, 'city': 'New York'}
dict1 = {"name": "Ahmed", "age": 25, "city": "New York"}
dict1.update({"name": "Ali", "age": 30, "salary": 20000})
print(dict1)
{'name': 'Ali', 'age': 30, 'city': 'New York', 'salary': 20000}
Dictionary Comprehension:
{key: value for key, value in iterable}
{x: x**2 for x in range(5)}
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
dict1 = {"name": "Ahmed", "age": 25, "city": "New York"}
dict1.update({"name": "Ali", "age": 30, "salary": 20000})
dict1.update(name = "Ali", age = 25, salary = 20000)
print(dict1)
keyboard_arrow_down Functions
In Python, functions allow us to write reusable blocks of code. They help organize logic, improve code readability, and make debugging
easier. Here’s a structured explanation with examples:
def function_name(what does the function need to operate): # Input arguements
block of code to be executed when the function is called
def greet(name): # Indentation
print("Hello, " + name + "!")
# Call
greet("Mostafa")
Hello, Mostafa!
def get_sum(x, y):
print(x+y)
# named, positional
get_sum(10, 20) # Positional
30
# named
get_sum(y = 20, x = 10)
30
get_sum(10, y = 20)
30
get_sum(x=10, 20)
File "<ipython-input-41-10fb62c8207a>", line 1
get_sum(x=10, 20)
^
SyntaxError: positional argument follows keyword argument
*args,
**kwargs
def get_sum(*args): # Can receive 0 or unlimited number of parameters. And creates a tuple with all the values.
print(args)
print(sum(args))
get_sum(55, 66, 120) # Positional
(55, 66, 120)
241
def get_sum(**kwargs): # Can receive 0 or unlimited number of parameters. And creates a tuple with all the values.
print(kwargs)
get_sum(name="Ahmed", age=25) # Named
{'name': 'Ahmed', 'age': 25}
def get_sum(a, b):
print(a+b)
get_sum(5, 6)
11
def salary_taxes(salary, percentage):
salary_after_taxes = salary - (salary * percentage / 100)
taxes = salary * percentage / 100
return salary_after_taxes, taxes
salary_after_taxes, taxes = salary_taxes(salary = 20000, percentage = 10)
keyboard_arrow_down Recursion, Iterators, and generators
Start coding or generate with AI.
keyboard_arrow_down Lambda, map, filter, reduce:
It can have any number of arguments but only one expression.
The result is automatically returned without using the return keyword.
It is mostly used for small, one-time use functions.
lambda arguments: expression
lambda → Defines the function.
arguments → Inputs to the function.
expression → A single operation that returns a result.
# Anonymous Function
double = lambda x: x**2
double(5)
25
add = lambda x, y: x + y
"""
def add(x, y):
return x + y
"""
add(10, 20)
30
The map() function applies a given function to each item in an iterable (like a list or
keyboard_arrow_down tuple) and returns a map object (which is an iterator).
map(function, iterable)
function → The function to apply.
iterable → The sequence (list, tuple, etc.) to apply the function to.
Returns an iterator, so it must be converted to a list if you want to see the results.
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, numbers))
print(squared)
[1, 4, 9, 16, 25]
lambda x: x**2 → Function that squares x.
map(lambda x: x**2, numbers) applies this function to each number.
list() converts the result into a list.
def squared(x):
return x**2
numbers = [1, 2, 3, 4, 5]
square = []
for i in numbers:
square.append(squared(i))
print(square)
squared = list(map(squared, 3))
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-61-c0d0e8286c0e> in <cell line: 0>()
----> 1 squared = list(map(squared, 3))
TypeError: 'int' object is not iterable
list1 = [1, 2, 3]
list2 = [4, 5, 6]
Using map and lambda sum the elements of the two lists.
[5, 7, 9]
list1 = [1, 2, 3]
list2 = [4, 5, 6]
list(map(lambda x, y: x+y, list1, list2))
[5, 7, 9]
words = ["hello", "world", "python"]
uppercase_words = list(map(lambda word: word.upper(), words))
print(uppercase_words) # Output: ['HELLO', 'WORLD', 'PYTHON']
# lambda that will check if a number is even or odd and if even return "even" and if odd return "odd".
even_or_odd = lambda x: "even" if x % 2 == 0 else "odd"
even_or_odd(5)
'odd'
list1 = [4, 5, 6, 7, 8, 9]
list(map(lambda x: "even" if x % 2 == 0 else "odd", list1))
['even', 'odd', 'even', 'odd', 'even', 'odd']
scores = [95, 82, 76, 89, 99]
"""
If s >= 90, return "A".
Else, if s >= 80, return "B".
Otherwise, return "C".
"""
scores = [95, 82, 76, 89, 99]
grades = list(map(lambda s: "A" if s >= 90 else ("B" if s >= 80 else "C"), scores))
print(grades)
# Output: ['A', 'B', 'C', 'B', 'A']
filter(function, iterable)
function: A function that returns True or False for each element.
iterable: A list, tuple, or other iterable to be filtered.
Returns a filtered iterator, which we usually convert to a list using list().
numbers = [55, 66, 77, 88, 99, 105]
filtered_numbers = list(filter(lambda x: x > 70, numbers))
print(filtered_numbers)
[77, 88, 99, 105]
x = 100
print(x>50)
numbers = [55, 66, 77, 88, 99, 105]
filtered_numbers = list(filter(lambda x: x%2==0, numbers))
print(filtered_numbers)
[66, 88]
def is_even(value):
return value % 2 == 0
numbers = [55, 66, 77, 88, 99, 105]
filtered_numbers = []
for i in numbers:
if is_even(i) == True:
filtered_numbers.append(i)
filtered_numbers
[66, 88]
The reduce() function is used to apply a function cumulatively to the elements of an iterable, reducing it to a single value.
from functools import reduce
reduce(function, iterable)
function: A function that takes two arguments and returns a single value.
iterable: A sequence (list, tuple, etc.) whose elements will be combined.
Returns: A single reduced value (e.g., sum, product, maximum, etc.).
from functools import reduce
numbers = [1, 2, 3, 4, 5]
sum_result = reduce(lambda x, y: x + y, numbers)
print(sum_result)
# Output: 15
def get_sum(x, y):
return x + y
numbers = [1, 2, 3, 4, 5]
sum1 = 0
for i in numbers: # i = 5
sum1 = get_sum(sum1, i) # 15
print(sum1)
15
from functools import reduce
numbers = [1, 2, 3, 4, 5]
product = reduce(lambda x, y: x * y, numbers)
print(product)
# Output: 120
120
# Using reduce find the maximum element in the following list: [3, 10, 2, 8, 6]
from functools import reduce
numbers = [3, 10, 2, 8, 6]
max_number = reduce(lambda x, y: x if x > y else y, numbers)
print(max_number)
{"a": 1, "b": 2, "a": 3}
{"a": 5}
data = {"a": 1, "b": 2}
data2 = {"a": 5, "c": 5}
all_keys = set(data.keys()).union(data2.keys())
all_keys
{'a', 'b', 'c'}
result = {key: sum(map(lambda d: d.get(key, 0), [data, data2])) for key in all_keys}
print(result)
{'b': 2, 'c': 5, 'a': 6}
Start coding or generate with AI.