0% found this document useful (0 votes)
3 views2 pages

Python Crash Course

This document provides a comprehensive overview of a crash course in Python, covering fundamental topics such as Python basics, core data types, operators, conditional statements, loops, and advanced concepts like functions and functional programming. It outlines learning objectives and includes practical examples and exercises for data manipulation and string operations. The course aims to equip learners with essential Python skills for programming and data handling.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views2 pages

Python Crash Course

This document provides a comprehensive overview of a crash course in Python, covering fundamental topics such as Python basics, core data types, operators, conditional statements, loops, and advanced concepts like functions and functional programming. It outlines learning objectives and includes practical examples and exercises for data manipulation and string operations. The course aims to equip learners with essential Python skills for programming and data handling.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Course Overview

This crash course covers the following fundamental Python topics:

Python Basics
Topic Description

Writing your first Python code Basic syntax and execution

Importing modules Using import statement

Understanding immutability Concept of unchangeable objects

Strings are immutable Why strings can't be modified

Mutable vs Immutable objects Key differences and examples

is vs == operator Identity vs equality comparison

*args vs **kwargs Positional vs keyword arguments

Core Data Types


Numbers
Integers - Whole numbers
Floats - Decimal numbers

Strings
String creation
Printing
Indexing
Escape sequences
String operations

Booleans
True and False values
Boolean operations

Lists
Indexing
Slicing
List manipulation
Copying / cloning lists

Tuples

Sets

Dictionaries
Creating dictionaries
Accessing values
Dictionary operations

Operators

Operator Type Examples

Comparison == , != , > , < , >= , <=

Logical and , or , not

Identity is , is not

Membership in , not in

Conditional Statements
┌─────────────────────────┐
│ if condition: │
│ # code block │
│ elif condition: │
│ # code block │
│ else: │
│ # code block │
└─────────────────────────┘

if - Primary condition
elif - Alternative conditions
else - Default fallback
Branching logic

Loops

Loop Type Syntax Use Case

for for item in sequence: Iterate over sequences

while while condition: Condition-based repetition

range() range(start, stop, step) Generate number sequences

Advanced Python Basics


List Comprehensions
[expression for item in iterable if condition]

Functions

Lambda Expressions
lambda arguments: expression

Functional Programming
map() - Transform items
filter() - Select items

Built-in Methods
String methods
List methods
Dictionary methods

Learning Objectives
After completing this session, you will be able to:

Basic Skills
Write basic Python code
Work with various data types
Convert data from one type to another
Use expressions and variables

Data Manipulation
Perform string operations and manipulation
Work with lists, tuples, sets, and dictionaries

Control Flow
Apply conditional statements
Use loops effectively

Advanced Concepts
Create and use functions
Apply functional programming tools like lambda , map , and filter

In [2]: print("hallo world")


print("hallo","world")
print("hallo","world",sep="&")
print("hallo {}".format("world"))

hallo world
hallo world
hallo&world
hallo world

Data Types

Numbers ( int - float )


In [3]: print(f"""
5 + 2 = {5 + 2}
5 - 2 = {5-2}
5 * 2 = {5*2}
5 / 2 = {5/2}
5 % 2 = {5%2}
5 // 2 = {5//2}
""")

5 + 2 = 7
5 - 2 = 3
5 * 2 = 10
5 / 2 = 2.5
5 % 2 = 1
5 // 2 = 2

In [6]: num = 1
num = 1.0
print(0.1+0.2)

0.30000000000000004

Use Decimal for exact arithmetic

In [7]: from decimal import Decimal

result = Decimal('0.1') + Decimal('0.2')


print(result)

0.3

Strings

String Creation

In [8]: #### note ( double_quotes ): It helps when your string contains quotes.
single_quotes = 'Hello'

double_quotes = "World"

triple_quotes = '''Multi
line
string'''
triple_double = """Another
multi-line"""

text = 'I\'m learning Python' # You would need escape character

text = "I'm learning Python" # String Contains Single Quote

text = 'I\'m learning "Python"' # String Contains Double Quote

print(text)

I'm learning "Python"

Indexing

In [10]: text = "Hallo"


print(text[0]) # P (first character)
print(text[-1]) # n (last character)
print(text[2]) # t (third character)
print(text[-2]) # o (second from end)

H
o
l
l

Slicing

In [34]: text = "Python"


print(text[0:3]) # Pyt (start:stop)
print(text[2:]) # thon (from index 2 to end)
print(text[:4]) # Pyth (from start to index 3)
print(text[::2]) # Pto (every 2nd character)
print(text[::-1]) # nohtyP (reverse string)

Pyt
thon
Pyth
Pto
nohtyP

STRING SLICING EXERCISES

Text = "Hello world"


Char: H e l l o w o r l d
Pos: 0 1 2 3 4 5 6 7 8 9 10
Neg: -11-10 -9 -8 -7 -6 -5 -4 -3 -2 -1

Category Syntax Output - Category Syntax Output

Basic Slicing text[0:5] - Negative Slicing text[-1:-4]

text[6:11] - text[-4:-1]

text[:5] - text[-11:-1]

text[6:] - text[:-4]

text[:] - text[-4:]

Negative Indexing text[-1] - Mixed Positive & Negative text[0:-4]

text[-4] - text[6:-2]

text[-11] - text[-11:5]

Step Slicing text[::2] - Tricky Examples text[-1:]

text[1::2] - text[:-1]

text[::-1] - text[-5:-2]

text[::-2] - text[3:9:2]

text[6::-1] - text[9:3:-1]

Text = "Hello world"


Char: H e l l o w o r l d
Pos: 0 1 2 3 4 5 6 7 8 9 10
Neg: -11-10 -9 -8 -7 -6 -5 -4 -3 -2 -1

Category Syntax Output Description - Category Syntax Output Description

Basic Slicing text[0:5] 'Hello' Start to position 5 - Negative Slicing text[-1:-4] '' Empty (backwards)

text[6:11] 'world' Position 6 to 11 - text[-4:-1] 'orl' 4th last to 1st last

text[:5] 'Hello' From start to 5 - text[-11:-1] 'Hello worl' 11th last to 1st last

text[6:] 'world' From 6 to end - text[:-4] 'Hello wo' All except last 4

text[:] 'Hello world' Entire string - text[-4:] 'orld' Last 4 characters

Negative Indexing text[-1] 'd' Last character - Mixed Positive & Negative text[0:-4] 'Hello wo' Start to 4th from end

text[-4] 'o' 4th from end - text[6:-2] 'wor' 6th to 2nd from end

text[-11] 'H' 11th from end - text[-11:5] 'Hello' 11th from end to 5th

Step Slicing text[::2] 'Hlowrd' Every 2nd character - Tricky Examples text[-1:] 'd' Last character as slice

text[1::2] 'el ol' Every 2nd from index 1 - text[:-1] 'Hello worl' All except last

text[::-1] 'dlrow olleH' Reverse string - text[-5:-2] 'wor' 5th last to 2nd last

text[::-2] 'drwo lH' Reverse every 2nd - text[3:9:2] 'lo o' Index 3 to 9, step 2

text[6::-1] ' olleH' From index 6 backwards - text[9:3:-1] 'lrow o' Index 9 to 3 backwards

String Operations

Basic Operations
Operation Example Output Description

Concatenation "Hello" + " " + "World" 'Hello World' Join strings

Repetition "Ha" * 3 'HaHaHa' Repeat string

Length len("Hello") 5 Get string length

String Methods
Method Example Output Description

upper() "Hello".upper() 'HELLO' Convert to uppercase

lower() "Hello".lower() 'hello' Convert to lowercase

strip() " spaces ".strip() 'spaces' Remove whitespace

replace() "hello world".replace("world", "Python") 'hello Python' Replace substring

split() "apple,banana,cherry".split(",") ['apple', 'banana', 'cherry'] Split into list

Checking Methods
Method Example Output Description

startswith() "Hello".startswith("He") True Check if starts with

endswith() "World".endswith("ld") True Check if ends with

isdigit() "123".isdigit() True Check if all digits

isalpha() "abc".isalpha() True Check if all letters

FIND vs INDEX
Method Found Not Found Raises Error?

find() Returns index position Returns -1 No

index() Returns index position ValueError Yes

Examples:

Operation Result Note

"Hello World".find("World") 6 Returns position

"Hello World".find("Python") -1 Not found, no error

"Hello World".find("o") 4 First occurrence

"Hello World".index("World") 6 Returns position

"Hello World".index("o") 4 First occurrence

"Hello World".index("Python") ValueError Raises error

Membership Operators
Operator Example Output Description

in "o" in "Hello" True Check if substring exists

not in "x" not in "Hello" True Check if substring doesn't exist

When to Use?
Use find() when:

You want to check if substring exists


You don't want your program to crash
You can handle -1 as 'not found'

Use index() when:

You're SURE the substring exists


You want an error if it doesn't exist

Casting
In [11]: num = 1
num1 = 1.0
string = "a"
string1 = "1"
string2 = "1.0"

# Converting numbers to strings


str(num) , str(num1)

# Converting strings to numbers


float(num1), int(string1) , int(float(string2))

Out[11]: (1.0, 1, 1)

Boolean data type


In [12]: (1 > 2) and (2 < 3)
(1 > 2) or (2 < 3)
(1 == 2) or (2 == 3) or (4 == 4)

Out[12]: True

Expression Output

bool(1)

bool(0)

bool("")

bool("a")

bool([])

bool([1, 2])

bool(100)

bool(-5)

bool(0.0)

In [46]: bool(1) , bool(0) , bool("") , bool("fady") ,bool([]) , bool([1,2]) ,bool(-5) , bool(0.0)

Out[46]: (True, False, False, True, False, True, True, False)

Collections : List vs Dict vs Tuples vs Sets

List
In [13]: # List Creation
# Sample list with mixed types
mixed_list = ["Michael Jackson", 10.1, 1982, [1, 2], ("A", 1)]
print("Mixed list:", mixed_list)

# Accessing Elements
print("ACCESSING ELEMENTS")
my_list = ['a', 'b', 'c']
print("my_list:", my_list)
print("my_list[0]:", my_list[0])

nest = [1, 2, 3, [4, 5, ['target']]]


print("nest:", nest)
print("nest[3]:", nest[3])
print("nest[3][2]:", nest[3][2])
print("nest[3][2][0]:", nest[3][2][0])

# Adding Elements
# Using extend()
L = ["Michael Jackson", 10.2]
print("Original L:", L)
[Link](['pop', 10])
print("After extend:", L)

# Using append()
L = ["Michael Jackson", 10.2]
print("\nOriginal L:", L)
[Link](['pop', 10])
print("After append:", L)

# Modifying Elements
print("MODIFYING ELEMENTS")

A = ["fady", 10, 1.2]


print('Before change:', A)
A[0] = 'hard rock'
print('After change:', A)

# Deleting Elements
print("DELETING ELEMENTS")

A = ["hossam", 10, 1.2]


print('Before change:', A)
del(A[0])
print('After change:', A)

# String Split
print("STRING SPLIT")
result = 'fady maher'.split()
print("'hard rock'.split():", result)

# extend() - adds each element of the list


list1 = [1, 2, 3]
[Link]([4, 5])
print("After extend([4, 5]):", list1)

# append() - adds the entire list as one element


list2 = [1, 2, 3]
[Link]([4, 5])
print("After append([4, 5]):", list2)

Mixed list: ['Michael Jackson', 10.1, 1982, [1, 2], ('A', 1)]
ACCESSING ELEMENTS
my_list: ['a', 'b', 'c']
my_list[0]: a
nest: [1, 2, 3, [4, 5, ['target']]]
nest[3]: [4, 5, ['target']]
nest[3][2]: ['target']
nest[3][2][0]: target
Original L: ['Michael Jackson', 10.2]
After extend: ['Michael Jackson', 10.2, 'pop', 10]

Original L: ['Michael Jackson', 10.2]


After append: ['Michael Jackson', 10.2, ['pop', 10]]
MODIFYING ELEMENTS
Before change: ['fady', 10, 1.2]
After change: ['hard rock', 10, 1.2]
DELETING ELEMENTS
Before change: ['hossam', 10, 1.2]
After change: [10, 1.2]
STRING SPLIT
'hard rock'.split(): ['fady', 'maher']
After extend([4, 5]): [1, 2, 3, 4, 5]
After append([4, 5]): [1, 2, 3, [4, 5]]

Tuples and Set

In [14]: s = {1,2,3,4,1,2}
t = (1,'a')
t[0]

Out[14]: 1

In [15]: t[0] = 0

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[15], line 1
----> 1 t[0] = 0

TypeError: 'tuple' object does not support item assignment

In [16]: s = "Fady"
s[0] = 'd'

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[16], line 2
1 s = "Fady"
----> 2 s[0] = 'd'

TypeError: 'str' object does not support item assignment

Dictionary
In [17]: my_dict = {
"key1": 1,
"key2": 1.0,
"key3": "fady",
"key4": "hossam",
"key5": True,
"key6": [1, 2.0]
}

print("my_dict:", my_dict)
print("Type:", type(my_dict))
print("Length:", len(my_dict))

my_dict: {'key1': 1, 'key2': 1.0, 'key3': 'fady', 'key4': 'hossam', 'key5': True, 'key6': [1, 2.0]}
Type: <class 'dict'>
Length: 6

In [19]: # ACCESSING VALUES


# Method 1: Using square brackets
print("my_dict['key3']:", my_dict['key3'])
print("my_dict['key6']:", my_dict['key6'])

# Method 2: Using get() method


print("my_dict.get('key4'):", my_dict.get('key4'))
print("my_dict.get('key10'):", my_dict.get('key10')) # Returns None if key doesn't exist

my_dict['key3']: fady
my_dict['key6']: [1, 2.0]
my_dict.get('key4'): hossam
my_dict.get('key10'): None

In [20]: # Get all keys


print("Keys:", my_dict.keys())
# Get all values
print("\nValues:", my_dict.values())
# Get key-value pairs as tuples
print("\nItems:", my_dict.items())

Keys: dict_keys(['key1', 'key2', 'key3', 'key4', 'key5', 'key6'])

Values: dict_values([1, 1.0, 'fady', 'hossam', True, [1, 2.0]])

Items: dict_items([('key1', 1), ('key2', 1.0), ('key3', 'fady'), ('key4', 'hossam'), ('key5', True), ('key6', [1, 2.0])])

In [ ]: # ADDING AND MODIFYING


my_dict["key7"] = "new value"
print("After adding key7:", my_dict)

my_dict["key3"] = "ahmed"
print("After modifying key3:", my_dict)

In [63]: # REMOVING ELEMENTS


# pop() - removes and returns value
removed_value = my_dict.pop('key2')

In [21]: # CHECKING MEMBERSHIP


print("Is 'key3' in my_dict?:", 'key3' in my_dict)
print("Is 'key10' in my_dict?:", 'key10' in my_dict)

Is 'key3' in my_dict?: True


Is 'key10' in my_dict?: False

MUTABLE vs IMMUTABLE
In [22]: # IMMUTABLE OBJECTS - Cannot be changed after creation

# Strings are IMMUTABLE


text = "Hello"
print(f"Original string: {text}")
print(f"ID of text: {id(text)}")
text = text + " World"
print(f"After : ID of text: {id(text)}") # Different ID - new object created

# Numbers are IMMUTABLE


num = 10
print(f"Original number: {num}")
print(f"ID of num: {id(num)}")
num = num + 5
print(f"After : ID of num: {id(num)}") # Different ID

# MUTABLE OBJECTS - Can be changed after creation

# Lists are MUTABLE


list_data = [1, 2, 3]
print(f"Original list: {list_data}")
print(f"ID of list: {id(list_data)}")
list_data[0] = 10
print(f"After : ID of list: {id(list_data)}") # Same ID - same object modified
# Note: ID stayed the same - object was modified in place!

# Dictionaries are MUTABLE


dict_data = {"name": "Alice", "age": 25}
print(f"Original dict: {dict_data}")
print(f"After : ID of dict: {id(dict_data)}")
dict_data["age"] = 26
dict_data["city"] = "Cairo"
print(f"ID of dict: {id(dict_data)}") # Same ID
print("Note: ID stayed the same - object was modified in place!")

# List aliasing (both variables point to same object)


list1 = [1, 2, 3]
list2 = list1 # list2 points to the SAME object
print(f"list1: {list1}, ID: {id(list1)}")
print(f"list2: {list2}, ID: {id(list2)}")

[Link](4)
print(f"After [Link](4):")
print(f"list1: {list1}") # list1 also changed!
print(f"list2: {list2}")

print("\n" + "-" * 70)

Original string: Hello


ID of text: 1818883001200
After : ID of text: 1817016067632
Original number: 10
ID of num: 140721730663624
After : ID of num: 140721730663784
Original list: [1, 2, 3]
ID of list: 1817024851072
After : ID of list: 1817024851072
Original dict: {'name': 'Alice', 'age': 25}
After : ID of dict: 1816974455424
ID of dict: 1816974455424
Note: ID stayed the same - object was modified in place!
list1: [1, 2, 3], ID: 1817024852992
list2: [1, 2, 3], ID: 1817024852992
After [Link](4):
list1: [1, 2, 3, 4]
list2: [1, 2, 3, 4]

----------------------------------------------------------------------

if,elif, else Statements

In [23]: num1 = 1
num2 = 2

if num1 == 3 :
print("num1 == 3")
else:
if num1 > num2 :
print("num1 > num2")
else:
print("num1 < num2")

num1 < num2

In [24]: num1 = 1
num2 = 2

if (num1 == 3) :
print("num1 == 3")
else:
if (num1 > num2) :
print("num1 > num2")
else:
print("num1 < num2")

num1 < num2

In [26]: if num1 == 3 : {
print("num1 == 3")
}
elif num1 > num2 : {
print("num1 > num2")
}
else:{
print("num1 < num2")
}

num1 < num2

LOOPS

In [27]: fruits = ["apple", "banana", "cherry", "orange"]


for fruit in fruits:
print(f" I like {fruit}")

I like apple
I like banana
I like cherry
I like orange

In [28]: fruits = ["apple", "banana", "cherry", "orange"]


for fruit in fruits:
print(f" I like {fruit}")
else:
print('finished')

I like apple
I like banana
I like cherry
I like orange
finished

In [29]: fruits = ["apple", "banana", "cherry", "orange"]


for fruit in fruits:
print(f" I like {fruit}")
if fruit == "banana":
break
else:
print('finished')

I like apple
I like banana

In [30]: # For loop with range(start, stop, step)


for i in range(5):
print(f" Number: {i}")

Number: 0
Number: 1
Number: 2
Number: 3
Number: 4

In [31]: for i in range(0, 10, 2):


print(f" Even number: {i}")

Even number: 0
Even number: 2
Even number: 4
Even number: 6
Even number: 8

In [32]: colors = ["red", "green", "blue"]


for index, color in enumerate(colors):
print(f" Index {index}: {color}")

Index 0: red
Index 1: green
Index 2: blue

In [33]: count = 0
print("Count from 0 to 4:")
while count < 5:
print(f" Count: {count}")
count += 1

Count from 0 to 4:
Count: 0
Count: 1
Count: 2
Count: 3
Count: 4

In [34]: num = 0
while num < 10:
num += 1
if num % 2 == 0:
continue # Skip even numbers
print(f" Odd: {num}")

Odd: 1
Odd: 3
Odd: 5
Odd: 7
Odd: 9

list comprehension
In [35]: # Traditional way with for loop
squares_loop = []
for i in range(10):
squares_loop.append(i ** 2)
print(f" {squares_loop}")

# List comprehension way


squares_comp = [i ** 2 for i in range(10)]
print(f" {squares_loop}")

[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]


[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

IS vs ==
== (Equality Operator)

Compares VALUES
Checks if two objects have the same content
Returns True if values are equal

is (Identity Operator)

Compares IDENTITIES (memory addresses)


Checks if two variables point to the SAME object
Returns True if both are the same object in memory

In [69]: a = 5
b = 5
print(f"a = {a}, b = {b}")
print(f"a == b: {a == b} (values equal)")
print(f"a is b: {a is b} (same object)") # -5 to 256
print(f"id(a): {id(a)}")
print(f"id(b): {id(b)}")

a = 5, b = 5
a == b: True (values equal)
a is b: True (same object)
id(a): 140721730663464
id(b): 140721730663464

In [70]: x = 1000
y = 1000
print(f"x = {x}, y = {y}")
print(f"x == y: {x == y} (values equal)")
print(f"x is y: {x is y} (different objects)")
print(f"id(x): {id(x)}")
print(f"id(y): {id(y)}")

x = 1000, y = 1000
x == y: True (values equal)
x is y: False (different objects)
id(x): 1817023736368
id(y): 1817023736016

In [71]: list1 = [1, 2, 3]


list2 = [1, 2, 3]
list3 = list1

print("list1 = [1, 2, 3]")


print("list2 = [1, 2, 3]")
print("list3 = list1")
print()

print(f"list1 == list2: {list1 == list2} (same values)")


print(f"list1 is list2: {list1 is list2} (different objects)")
print(f"id(list1): {id(list1)}")
print(f"id(list2): {id(list2)}")
print()

print(f"list1 == list3: {list1 == list3} (same values)")


print(f"list1 is list3: {list1 is list3} (SAME object)")
print(f"id(list1): {id(list1)}")
print(f"id(list3): {id(list3)}")

list1 = [1, 2, 3]
list2 = [1, 2, 3]
list3 = list1

list1 == list2: True (same values)


list1 is list2: False (different objects)
id(list1): 1817024849600
id(list2): 1818882975232

list1 == list3: True (same values)


list1 is list3: True (SAME object)
id(list1): 1817024849600
id(list3): 1817024849600

functions
In [72]: def square(number=2):
return number ** 2

'''
def square(number : int = 2):
return number ** 2
'''
# Way 1: Call with default parameter
result = square()
print("square() :", result)

# Way 2: Call with positional argument


result = square(3)
print("square(3) :", result)

# Way 3: Call with keyword argument


result = square(number=5)
print("square(number=5):", result)

square() : 4
square(3) : 9
square(number=5): 25

In [74]: # Function with PRINT


def square_print(number=2):
print(number ** 2)

out = square_print(3) # Prints 9 during execution


print(f" out2 = {out}") # None
print(f" Type: {type(out)}")

9
out2 = None
Type: <class 'NoneType'>

use mutable objects as default parameters


In [75]: def func(l=[]):
[Link](5)
return l

result1 = func()
print(f" Result: {result1}")
print(f" ID: {id(result1)}")

result3 = func([1])
print(f" Result: {result3}")
print(f" ID: {id(result3)}")

result4 = func()
print(f" Result: {result4}")
print(f" ID: {id(result4)}")

# The default list [] is created ONCE when the function is DEFINED, not each time the function is CALLED!

Result: [5]
ID: 1817024847296
Result: [1, 5]
ID: 1817024853760
Result: [5, 5]
ID: 1817024847296

In [76]: # It stores the default value in


func.__defaults__

Out[76]: ([5, 5],)

In [77]: result4 = func()


print(f" Result: {result4}")
print(f" ID: {id(result4)}")

Result: [5, 5, 5]
ID: 1817024847296

In [78]: func.__defaults__

Out[78]: ([5, 5, 5],)

**KWARGS (KEYWORD ARGUMENTS) vs *ARGS (Positional Arguments)


In [79]: def sum_all(*args):
print(f"Type of args: {type(args)}")
print(f"Contents: {args}")
total = sum(args)
return total

result = sum_all(1, 2, 3, 4, 5)
print(f"Sum: {result}")

Type of args: <class 'tuple'>


Contents: (1, 2, 3, 4, 5)
Sum: 15

In [80]: def info_v1(**kwargs):


print(f"Type of kwargs: {type(kwargs)}")
print(f"Contents: {kwargs}")
for key, value in [Link]():
print(f" {key}: {value}")

info_v1(name="fady maher", age=25)

Type of kwargs: <class 'dict'>


Contents: {'name': 'fady maher', 'age': 25}
name: fady maher
age: 25

lambda
In [81]: funcv1 = lambda number : number * 2

In [82]: funcv1(2)

Out[82]: 4

In [83]: funcv2 = lambda number,mul : number * mul

In [84]: funcv2(2,3)

Out[84]: 6

map
map(function, sequence)

TRANSFORMS each item


Returns transformed version of EVERY item
Use when: You want to CHANGE every item

In [85]: seq = [1,2,3,4,5]


seq_v2 = map(funcv1,seq)
print(list(seq_v2))

[2, 4, 6, 8, 10]

filter :
filter(function, sequence)

FILTERS items based on condition


Function returns True/False (boolean)
Returns only items where function returns True
Use when: You want to SELECT certain items

In [86]: print(list(filter(lambda item: item%2 == 0,seq)))

[2, 4]

Import
In [87]: import app
In [88]: [Link]()

hallo world

You might also like