SlideShare a Scribd company logo
Advanced Python after beginner python for intermediate learners
From the map() function, which applies a specified function to each
element of an iterable and returns a new iterable with the modified
elements, to the enumerate() function which adds a counter to an
iterable and returns an iterable of tuples, these functions can help you
write cleaner and more concise code.
Let’s take a closer look at these advanced Python functions and see how
to use them in your code.
map()
The map() function applies a specified function to each element of an iterable (such as a list, tuple, or
string) and returns a new iterable with the modified elements.
For example, you can use map() to apply the len() function to a list of strings and get a list of the lengths of
each string:
You can also use map() with multiple iterables by providing multiple function arguments. In this case, the
function should accept as many arguments as there are iterables. The map() function will then apply the
function to the elements of the iterables in parallel, with the first element of each iterable being passed as
arguments to the function, the second element of each iterable being passed as arguments to the function,
and so on.
For example, you can use map() to apply a function to two lists element-wise:
def multiply(x, y):
return x * y
a = [1, 2, 3]
b = [10, 20, 30]
result = map(multiply, a, b)
print(result) # [10, 40, 90]
reduce()
The reduce() function is a part of the functools module in Python and allows you to apply a function to a
sequence of elements in order to reduce them to a single value.
For example, you can use reduce() to multiply all the elements of a list:
You can also specify an initial value as the third argument to reduce(). In this case, the initial value will be
used as the first argument to the function and the first element of the iterable will be used as the second
argument.
For example, you can use reduce() to calculate the sum of a list of numbers:
filter()
The filter() function filters an iterable by removing elements that do not satisfy a specified condition. It
returns a new iterable with only the elements that satisfy the condition.
For example, you can use filter() to remove all the even numbers from a list:
def is_odd(x):
return x % 2 == 1
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
odd_numbers = filter(is_odd, a)
print(odd_numbers) # [1, 3, 5, 7,
9]
You can also use filter() with a lambda function as the first argument:
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
odd_numbers = filter(lambda x: x %
2 == 1, a)
print(odd_numbers) # [1, 3, 5, 7,
9]
zip()
The zip() function combines multiple iterables into a single iterable of tuples. The zip() function stops
when the shortest iterable is exhausted.
For example, you can use zip() to combine two lists into a list of tuples:
a = [1, 2, 3]
b = ['a', 'b', 'c']
zipped = zip(a, b)
print(zipped) # [(1, 'a'), (2,
'b'), (3, 'c')]
You can also use zip() with more than two iterables:
a = [1, 2, 3]
b = ['a', 'b', 'c']
c = [True, False, True]
zipped = zip(a, b, c)
print(zipped) # [(1, 'a', True),
(2, 'b', False), (3, 'c', True)]
You can unpack the tuples in a zip() object by using the * operator in a function call or a list
comprehension:
enumerate()
The enumerate() function adds a counter to an iterable and returns an iterable of tuples, where each tuple
consists of the counter and the original element.
For example, you can use enumerate() to loop over a list and print the index and value of each element:
You can also specify a start value for the counter as the second argument to enumerate():
we covered some advanced Python functions that can be useful in your code. We looked at the map(),
reduce(), filter(), zip(), and enumerate() functions, and provided examples of how to use them. These
functions can help you write more efficient and concise code, and are worth exploring further.
Modules and Libraries in Python
1. What is a Module?
A module in Python is a file that contains Python code (functions, classes, or variables)
that you can reuse in your programs.
Any Python file with the .py extension is a module.
You can import a module into another program to access its functions or classes.
2. What is a Library?
A library is a collection of modules or packages that provide pre-written functionality to
simplify coding tasks.
Example: Libraries like NumPy for arrays, Pandas for data analysis, and Matplotlib for
plotting.
3. Importing Libraries and Modules
You can import libraries or modules using the import statement.
Basic Import Syntax:
Importing Specific Functions or Classes
https://www.learnpython.dev/03-intermediate-python/50-libraries-module
s/30-modules-and-imports/
We will study little from this site now…
4. Installing External Libraries Using pip
What is pip?
● pip is Python's package manager used to install external libraries that are not built
into Python.
● Libraries like NumPy, Pandas, and Matplotlib are installed using pip.
Installing a Library
pip install library_name
For example:
pip install numpy
pip install pandas
Advanced Strings in Python
Decimal Formatting:
Formatting decimal or floating point numbers with f-strings is easy - you can pass in both a
field width and a precision. The format is {value:width.precision}. Let’s format pi (3.1415926)
to two decimal places - we’ll set the width to 1 because we don’t need padding, and the
precision to 3, giving us the one number to the left of the decimal and the two numbers to the
right
Note how the
second one is
padded with
extra spaces -
the number is
four characters
long (including
the period), so
the formatter
added six extra
spaces to equal
the total width
of 10.
Multiline Strings
Sometimes it’s easier to break up large statements into multiple lines. Just prepend every line with
f:
Trimming a string
Python strings have some very useful functions for trimming whitespace. strip() returns a new
string after removing any leading and trailing whitespace. rstrip() and does the same but only
removes trailing whitespace, and lstrip() only trims leading whitespace. We’ll print our string inside
>< characters to make it clear:
Note the different spaces inside of the brackets. These functions also accept an optional argument of
characters to remove. Let’s remove all leading or trailing commas:
Replacing Characters
Strings have a useful function for replacing characters - just call replace() on any string and pass in what
you want replace, and what you want to replace it with:
str.format() and % formatting
Python has two older methods for string formatting that you’ll probably come across at some point.
str.format() is the more verbose older cousin to f-strings - variables appear in brackets in the string but
must be passed in to the format() call. For example:
Note that the variable name inside the string is local to the string - it must be assigned to an outside
variable inside the format() call, hence .format(name=name).
%-formatting is a much older method of string interpolating and isn’t used much anymore. It’s very similar
to the methods used in C/C++. Here, we’ll use %s as our placeholder for a string, and pass the name
variable in to the formatter by placing it after the % symbol.
*******************************************************************
Advanced Looping with List Comprehensions
List Comprehensions
List comprehensions are a unique way to create lists in Python. A list comprehension consists of brackets
containing an expression followed by a for clause, then zero or more for or if clauses. The expressions can
be any kind of Python object. List comprehensions will commonly take the form of [<value> for <vars>
in <iter>].
A simple case: Say we want to turn a list of strings into a list of string lengths. We could do this with a for
loop:
We can do this much easier with a list comprehension:
We can also use comprehensions to perform operations, and the lists we assemble can be composed of any
type of Python object. For example:
In the above example, we assemble a list of tuples - each tuple contains the element “length” as well as
each number from the len() function multiplied by two.
Conditionals
You can also use conditionals (if statements) in your list comprehensions. For example, to quickly make a list of
only the even lengths, you could do:
Here, we check divide every string length by 2, and check to see if the remainder is 0 (using the modulo
operator).
String Joining with a List Comprehension
Back in our exercise on converting between types, we introduced the string.join() function.
You can call this function on any string, pass it a list, and it will spit out a string with every
element from the list “joined” by the string. For example, to get a comma-delimited list of
numbers, you might be tempted to do:
Unfortunately, you can’t join a list of numbers without first converting them to strings. But
you can do this easily with a list comprehension:
Some mathematical functions, such as sum, min, and max, accept lists of numbers to operate
on. For example, to get the sum of numbers between zero and five, you could do:
But remember, anywhere you can use a list, you can use a list comprehension.
Say you want to get sum, minimum, and maximum of every number between 0 and 100 that
is evenly divisible by 3? No sense typing out a whole list in advance, just use a
comprehension:
Exception Handling:
Many languages have the concept of the “Try-Catch” block. Python uses four keywords:
try, except, else, and finally. Code that can possibly throw an exception goes in the try
block. except gets the code that runs if an exception is raised. else is an optional block
that runs if no exception was raised in the try block, and finally is an optional block of
code that will run last, regardless of if an exception was raised. We’ll focus on try and
except for this chapter.
First, the try clause is executed. If no exception occurs, the except clause is skipped and
execution of the try statement is finished. If an exception occurs in the try clause, the rest of
the clause is skipped. If the exception’s type matches the exception named after the except
keyword, then the except clause is executed. If the exception doesn’t match, then the
exception is unhandled and execution stops.
The except Clause
An except clause may have multiple exceptions, given as a parenthesized tuple:
A try statement can also have more than one except clause:
Finally
Finally, we have finally. finally is an optional block that runs after try, except, and else,
regardless of if an exception is thrown or not. This is good for doing any cleanup that
you want to happen, whether or not an exception is thrown.
As you can see, the Goodbye! gets printed just before the unhandled
KeyboardInterrupt gets propagated up and triggers the traceback.

More Related Content

Similar to Advanced Python after beginner python for intermediate learners (20)

justbasics.pdf
justbasics.pdfjustbasics.pdf
justbasics.pdf
DrRajkumarKhatri
 
python.pdf
python.pdfpython.pdf
python.pdf
wekarep985
 
Introduction_to_Python_operators_datatypes.pptx
Introduction_to_Python_operators_datatypes.pptxIntroduction_to_Python_operators_datatypes.pptx
Introduction_to_Python_operators_datatypes.pptx
MadhusmitaSahu40
 
"Automata Basics and Python Applications"
"Automata Basics and Python Applications""Automata Basics and Python Applications"
"Automata Basics and Python Applications"
ayeshasiraj34
 
Q-Step_WS_02102019_Practical_introduction_to_Python.pdf
Q-Step_WS_02102019_Practical_introduction_to_Python.pdfQ-Step_WS_02102019_Practical_introduction_to_Python.pdf
Q-Step_WS_02102019_Practical_introduction_to_Python.pdf
Michpice
 
Functions, List and String methods
Functions, List and String methodsFunctions, List and String methods
Functions, List and String methods
PranavSB
 
Python cheatsheat.pdf
Python cheatsheat.pdfPython cheatsheat.pdf
Python cheatsheat.pdf
HimoZZZ
 
Python Interview Questions And Answers
Python Interview Questions And AnswersPython Interview Questions And Answers
Python Interview Questions And Answers
H2Kinfosys
 
Python Objects
Python ObjectsPython Objects
Python Objects
MuhammadBakri13
 
Python Workshop
Python  Workshop Python  Workshop
Python Workshop
Assem CHELLI
 
python_computer engineering_semester_computer_language.pptx
python_computer engineering_semester_computer_language.pptxpython_computer engineering_semester_computer_language.pptx
python_computer engineering_semester_computer_language.pptx
MadhusmitaSahu40
 
Raspberry Pi - Lecture 5 Python for Raspberry Pi
Raspberry Pi - Lecture 5 Python for Raspberry PiRaspberry Pi - Lecture 5 Python for Raspberry Pi
Raspberry Pi - Lecture 5 Python for Raspberry Pi
Mohamed Abdallah
 
ComandosDePython_ComponentesBasicosImpl.ppt
ComandosDePython_ComponentesBasicosImpl.pptComandosDePython_ComponentesBasicosImpl.ppt
ComandosDePython_ComponentesBasicosImpl.ppt
oscarJulianPerdomoCh1
 
Python: An introduction A summer workshop
Python: An  introduction A summer workshopPython: An  introduction A summer workshop
Python: An introduction A summer workshop
ForrayFerenc
 
cover every basics of python with this..
cover every basics of python with this..cover every basics of python with this..
cover every basics of python with this..
karkimanish411
 
Python 101++: Let's Get Down to Business!
Python 101++: Let's Get Down to Business!Python 101++: Let's Get Down to Business!
Python 101++: Let's Get Down to Business!
Paige Bailey
 
Python Training
Python TrainingPython Training
Python Training
TIB Academy
 
Python Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, DictionaryPython Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, Dictionary
Soba Arjun
 
ppt_pspp.pdf
ppt_pspp.pdfppt_pspp.pdf
ppt_pspp.pdf
ShereenAhmedMohamed
 
Python Tutorial Part 1
Python Tutorial Part 1Python Tutorial Part 1
Python Tutorial Part 1
Haitham El-Ghareeb
 
Introduction_to_Python_operators_datatypes.pptx
Introduction_to_Python_operators_datatypes.pptxIntroduction_to_Python_operators_datatypes.pptx
Introduction_to_Python_operators_datatypes.pptx
MadhusmitaSahu40
 
"Automata Basics and Python Applications"
"Automata Basics and Python Applications""Automata Basics and Python Applications"
"Automata Basics and Python Applications"
ayeshasiraj34
 
Q-Step_WS_02102019_Practical_introduction_to_Python.pdf
Q-Step_WS_02102019_Practical_introduction_to_Python.pdfQ-Step_WS_02102019_Practical_introduction_to_Python.pdf
Q-Step_WS_02102019_Practical_introduction_to_Python.pdf
Michpice
 
Functions, List and String methods
Functions, List and String methodsFunctions, List and String methods
Functions, List and String methods
PranavSB
 
Python cheatsheat.pdf
Python cheatsheat.pdfPython cheatsheat.pdf
Python cheatsheat.pdf
HimoZZZ
 
Python Interview Questions And Answers
Python Interview Questions And AnswersPython Interview Questions And Answers
Python Interview Questions And Answers
H2Kinfosys
 
python_computer engineering_semester_computer_language.pptx
python_computer engineering_semester_computer_language.pptxpython_computer engineering_semester_computer_language.pptx
python_computer engineering_semester_computer_language.pptx
MadhusmitaSahu40
 
Raspberry Pi - Lecture 5 Python for Raspberry Pi
Raspberry Pi - Lecture 5 Python for Raspberry PiRaspberry Pi - Lecture 5 Python for Raspberry Pi
Raspberry Pi - Lecture 5 Python for Raspberry Pi
Mohamed Abdallah
 
ComandosDePython_ComponentesBasicosImpl.ppt
ComandosDePython_ComponentesBasicosImpl.pptComandosDePython_ComponentesBasicosImpl.ppt
ComandosDePython_ComponentesBasicosImpl.ppt
oscarJulianPerdomoCh1
 
Python: An introduction A summer workshop
Python: An  introduction A summer workshopPython: An  introduction A summer workshop
Python: An introduction A summer workshop
ForrayFerenc
 
cover every basics of python with this..
cover every basics of python with this..cover every basics of python with this..
cover every basics of python with this..
karkimanish411
 
Python 101++: Let's Get Down to Business!
Python 101++: Let's Get Down to Business!Python 101++: Let's Get Down to Business!
Python 101++: Let's Get Down to Business!
Paige Bailey
 
Python Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, DictionaryPython Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, Dictionary
Soba Arjun
 

Recently uploaded (20)

Azure vs AWS Which Cloud Platform Is Best for Your Business in 2025
Azure vs AWS  Which Cloud Platform Is Best for Your Business in 2025Azure vs AWS  Which Cloud Platform Is Best for Your Business in 2025
Azure vs AWS Which Cloud Platform Is Best for Your Business in 2025
Infrassist Technologies Pvt. Ltd.
 
AI Agents in Logistics and Supply Chain Applications Benefits and Implementation
AI Agents in Logistics and Supply Chain Applications Benefits and ImplementationAI Agents in Logistics and Supply Chain Applications Benefits and Implementation
AI Agents in Logistics and Supply Chain Applications Benefits and Implementation
Christine Shepherd
 
Introduction to Internet of things .ppt.
Introduction to Internet of things .ppt.Introduction to Internet of things .ppt.
Introduction to Internet of things .ppt.
hok12341073
 
Kubernetes Security Act Now Before It’s Too Late
Kubernetes Security Act Now Before It’s Too LateKubernetes Security Act Now Before It’s Too Late
Kubernetes Security Act Now Before It’s Too Late
Michael Furman
 
Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025
Safe Software
 
Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...
Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...
Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...
NTT DATA Technology & Innovation
 
Oracle Cloud Infrastructure Generative AI Professional
Oracle Cloud Infrastructure Generative AI ProfessionalOracle Cloud Infrastructure Generative AI Professional
Oracle Cloud Infrastructure Generative AI Professional
VICTOR MAESTRE RAMIREZ
 
Murdledescargadarkweb.pdfvolumen1 100 elementary
Murdledescargadarkweb.pdfvolumen1 100 elementaryMurdledescargadarkweb.pdfvolumen1 100 elementary
Murdledescargadarkweb.pdfvolumen1 100 elementary
JorgeSemperteguiMont
 
Providing an OGC API Processes REST Interface for FME Flow
Providing an OGC API Processes REST Interface for FME FlowProviding an OGC API Processes REST Interface for FME Flow
Providing an OGC API Processes REST Interface for FME Flow
Safe Software
 
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Agentic AI: Beyond the Buzz- LangGraph Studio V2Agentic AI: Beyond the Buzz- LangGraph Studio V2
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Shashikant Jagtap
 
Viral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Viral>Wondershare Filmora 14.5.18.12900 Crack Free DownloadViral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Viral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Puppy jhon
 
Your startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean accountYour startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean account
angelo60207
 
Crypto Super 500 - 14th Report - June2025.pdf
Crypto Super 500 - 14th Report - June2025.pdfCrypto Super 500 - 14th Report - June2025.pdf
Crypto Super 500 - 14th Report - June2025.pdf
Stephen Perrenod
 
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdfHow Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
Rejig Digital
 
Introduction to Typescript - GDG On Campus EUE
Introduction to Typescript - GDG On Campus EUEIntroduction to Typescript - GDG On Campus EUE
Introduction to Typescript - GDG On Campus EUE
Google Developer Group On Campus European Universities in Egypt
 
Enabling BIM / GIS integrations with Other Systems with FME
Enabling BIM / GIS integrations with Other Systems with FMEEnabling BIM / GIS integrations with Other Systems with FME
Enabling BIM / GIS integrations with Other Systems with FME
Safe Software
 
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdfBoosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Alkin Tezuysal
 
Edge-banding-machines-edgeteq-s-200-en-.pdf
Edge-banding-machines-edgeteq-s-200-en-.pdfEdge-banding-machines-edgeteq-s-200-en-.pdf
Edge-banding-machines-edgeteq-s-200-en-.pdf
AmirStern2
 
Oracle Cloud and AI Specialization Program
Oracle Cloud and AI Specialization ProgramOracle Cloud and AI Specialization Program
Oracle Cloud and AI Specialization Program
VICTOR MAESTRE RAMIREZ
 
Artificial Intelligence in the Nonprofit Boardroom.pdf
Artificial Intelligence in the Nonprofit Boardroom.pdfArtificial Intelligence in the Nonprofit Boardroom.pdf
Artificial Intelligence in the Nonprofit Boardroom.pdf
OnBoard
 
Azure vs AWS Which Cloud Platform Is Best for Your Business in 2025
Azure vs AWS  Which Cloud Platform Is Best for Your Business in 2025Azure vs AWS  Which Cloud Platform Is Best for Your Business in 2025
Azure vs AWS Which Cloud Platform Is Best for Your Business in 2025
Infrassist Technologies Pvt. Ltd.
 
AI Agents in Logistics and Supply Chain Applications Benefits and Implementation
AI Agents in Logistics and Supply Chain Applications Benefits and ImplementationAI Agents in Logistics and Supply Chain Applications Benefits and Implementation
AI Agents in Logistics and Supply Chain Applications Benefits and Implementation
Christine Shepherd
 
Introduction to Internet of things .ppt.
Introduction to Internet of things .ppt.Introduction to Internet of things .ppt.
Introduction to Internet of things .ppt.
hok12341073
 
Kubernetes Security Act Now Before It’s Too Late
Kubernetes Security Act Now Before It’s Too LateKubernetes Security Act Now Before It’s Too Late
Kubernetes Security Act Now Before It’s Too Late
Michael Furman
 
Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025
Safe Software
 
Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...
Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...
Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...
NTT DATA Technology & Innovation
 
Oracle Cloud Infrastructure Generative AI Professional
Oracle Cloud Infrastructure Generative AI ProfessionalOracle Cloud Infrastructure Generative AI Professional
Oracle Cloud Infrastructure Generative AI Professional
VICTOR MAESTRE RAMIREZ
 
Murdledescargadarkweb.pdfvolumen1 100 elementary
Murdledescargadarkweb.pdfvolumen1 100 elementaryMurdledescargadarkweb.pdfvolumen1 100 elementary
Murdledescargadarkweb.pdfvolumen1 100 elementary
JorgeSemperteguiMont
 
Providing an OGC API Processes REST Interface for FME Flow
Providing an OGC API Processes REST Interface for FME FlowProviding an OGC API Processes REST Interface for FME Flow
Providing an OGC API Processes REST Interface for FME Flow
Safe Software
 
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Agentic AI: Beyond the Buzz- LangGraph Studio V2Agentic AI: Beyond the Buzz- LangGraph Studio V2
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Shashikant Jagtap
 
Viral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Viral>Wondershare Filmora 14.5.18.12900 Crack Free DownloadViral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Viral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Puppy jhon
 
Your startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean accountYour startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean account
angelo60207
 
Crypto Super 500 - 14th Report - June2025.pdf
Crypto Super 500 - 14th Report - June2025.pdfCrypto Super 500 - 14th Report - June2025.pdf
Crypto Super 500 - 14th Report - June2025.pdf
Stephen Perrenod
 
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdfHow Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
Rejig Digital
 
Enabling BIM / GIS integrations with Other Systems with FME
Enabling BIM / GIS integrations with Other Systems with FMEEnabling BIM / GIS integrations with Other Systems with FME
Enabling BIM / GIS integrations with Other Systems with FME
Safe Software
 
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdfBoosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Alkin Tezuysal
 
Edge-banding-machines-edgeteq-s-200-en-.pdf
Edge-banding-machines-edgeteq-s-200-en-.pdfEdge-banding-machines-edgeteq-s-200-en-.pdf
Edge-banding-machines-edgeteq-s-200-en-.pdf
AmirStern2
 
Oracle Cloud and AI Specialization Program
Oracle Cloud and AI Specialization ProgramOracle Cloud and AI Specialization Program
Oracle Cloud and AI Specialization Program
VICTOR MAESTRE RAMIREZ
 
Artificial Intelligence in the Nonprofit Boardroom.pdf
Artificial Intelligence in the Nonprofit Boardroom.pdfArtificial Intelligence in the Nonprofit Boardroom.pdf
Artificial Intelligence in the Nonprofit Boardroom.pdf
OnBoard
 
Ad

Advanced Python after beginner python for intermediate learners

  • 2. From the map() function, which applies a specified function to each element of an iterable and returns a new iterable with the modified elements, to the enumerate() function which adds a counter to an iterable and returns an iterable of tuples, these functions can help you write cleaner and more concise code. Let’s take a closer look at these advanced Python functions and see how to use them in your code.
  • 3. map() The map() function applies a specified function to each element of an iterable (such as a list, tuple, or string) and returns a new iterable with the modified elements. For example, you can use map() to apply the len() function to a list of strings and get a list of the lengths of each string:
  • 4. You can also use map() with multiple iterables by providing multiple function arguments. In this case, the function should accept as many arguments as there are iterables. The map() function will then apply the function to the elements of the iterables in parallel, with the first element of each iterable being passed as arguments to the function, the second element of each iterable being passed as arguments to the function, and so on. For example, you can use map() to apply a function to two lists element-wise: def multiply(x, y): return x * y a = [1, 2, 3] b = [10, 20, 30] result = map(multiply, a, b) print(result) # [10, 40, 90]
  • 5. reduce() The reduce() function is a part of the functools module in Python and allows you to apply a function to a sequence of elements in order to reduce them to a single value. For example, you can use reduce() to multiply all the elements of a list:
  • 6. You can also specify an initial value as the third argument to reduce(). In this case, the initial value will be used as the first argument to the function and the first element of the iterable will be used as the second argument. For example, you can use reduce() to calculate the sum of a list of numbers:
  • 7. filter() The filter() function filters an iterable by removing elements that do not satisfy a specified condition. It returns a new iterable with only the elements that satisfy the condition. For example, you can use filter() to remove all the even numbers from a list: def is_odd(x): return x % 2 == 1 a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] odd_numbers = filter(is_odd, a) print(odd_numbers) # [1, 3, 5, 7, 9] You can also use filter() with a lambda function as the first argument: a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] odd_numbers = filter(lambda x: x % 2 == 1, a) print(odd_numbers) # [1, 3, 5, 7, 9]
  • 8. zip() The zip() function combines multiple iterables into a single iterable of tuples. The zip() function stops when the shortest iterable is exhausted. For example, you can use zip() to combine two lists into a list of tuples: a = [1, 2, 3] b = ['a', 'b', 'c'] zipped = zip(a, b) print(zipped) # [(1, 'a'), (2, 'b'), (3, 'c')] You can also use zip() with more than two iterables: a = [1, 2, 3] b = ['a', 'b', 'c'] c = [True, False, True] zipped = zip(a, b, c) print(zipped) # [(1, 'a', True), (2, 'b', False), (3, 'c', True)]
  • 9. You can unpack the tuples in a zip() object by using the * operator in a function call or a list comprehension:
  • 10. enumerate() The enumerate() function adds a counter to an iterable and returns an iterable of tuples, where each tuple consists of the counter and the original element. For example, you can use enumerate() to loop over a list and print the index and value of each element:
  • 11. You can also specify a start value for the counter as the second argument to enumerate(): we covered some advanced Python functions that can be useful in your code. We looked at the map(), reduce(), filter(), zip(), and enumerate() functions, and provided examples of how to use them. These functions can help you write more efficient and concise code, and are worth exploring further.
  • 13. 1. What is a Module? A module in Python is a file that contains Python code (functions, classes, or variables) that you can reuse in your programs. Any Python file with the .py extension is a module. You can import a module into another program to access its functions or classes. 2. What is a Library? A library is a collection of modules or packages that provide pre-written functionality to simplify coding tasks. Example: Libraries like NumPy for arrays, Pandas for data analysis, and Matplotlib for plotting. 3. Importing Libraries and Modules You can import libraries or modules using the import statement.
  • 14. Basic Import Syntax: Importing Specific Functions or Classes
  • 16. 4. Installing External Libraries Using pip What is pip? ● pip is Python's package manager used to install external libraries that are not built into Python. ● Libraries like NumPy, Pandas, and Matplotlib are installed using pip. Installing a Library pip install library_name For example: pip install numpy pip install pandas
  • 18. Decimal Formatting: Formatting decimal or floating point numbers with f-strings is easy - you can pass in both a field width and a precision. The format is {value:width.precision}. Let’s format pi (3.1415926) to two decimal places - we’ll set the width to 1 because we don’t need padding, and the precision to 3, giving us the one number to the left of the decimal and the two numbers to the right Note how the second one is padded with extra spaces - the number is four characters long (including the period), so the formatter added six extra spaces to equal the total width of 10.
  • 19. Multiline Strings Sometimes it’s easier to break up large statements into multiple lines. Just prepend every line with f:
  • 20. Trimming a string Python strings have some very useful functions for trimming whitespace. strip() returns a new string after removing any leading and trailing whitespace. rstrip() and does the same but only removes trailing whitespace, and lstrip() only trims leading whitespace. We’ll print our string inside >< characters to make it clear: Note the different spaces inside of the brackets. These functions also accept an optional argument of characters to remove. Let’s remove all leading or trailing commas:
  • 21. Replacing Characters Strings have a useful function for replacing characters - just call replace() on any string and pass in what you want replace, and what you want to replace it with: str.format() and % formatting Python has two older methods for string formatting that you’ll probably come across at some point. str.format() is the more verbose older cousin to f-strings - variables appear in brackets in the string but must be passed in to the format() call. For example:
  • 22. Note that the variable name inside the string is local to the string - it must be assigned to an outside variable inside the format() call, hence .format(name=name). %-formatting is a much older method of string interpolating and isn’t used much anymore. It’s very similar to the methods used in C/C++. Here, we’ll use %s as our placeholder for a string, and pass the name variable in to the formatter by placing it after the % symbol. *******************************************************************
  • 23. Advanced Looping with List Comprehensions
  • 24. List Comprehensions List comprehensions are a unique way to create lists in Python. A list comprehension consists of brackets containing an expression followed by a for clause, then zero or more for or if clauses. The expressions can be any kind of Python object. List comprehensions will commonly take the form of [<value> for <vars> in <iter>]. A simple case: Say we want to turn a list of strings into a list of string lengths. We could do this with a for loop: We can do this much easier with a list comprehension:
  • 25. We can also use comprehensions to perform operations, and the lists we assemble can be composed of any type of Python object. For example: In the above example, we assemble a list of tuples - each tuple contains the element “length” as well as each number from the len() function multiplied by two. Conditionals You can also use conditionals (if statements) in your list comprehensions. For example, to quickly make a list of only the even lengths, you could do: Here, we check divide every string length by 2, and check to see if the remainder is 0 (using the modulo operator).
  • 26. String Joining with a List Comprehension Back in our exercise on converting between types, we introduced the string.join() function. You can call this function on any string, pass it a list, and it will spit out a string with every element from the list “joined” by the string. For example, to get a comma-delimited list of numbers, you might be tempted to do: Unfortunately, you can’t join a list of numbers without first converting them to strings. But you can do this easily with a list comprehension:
  • 27. Some mathematical functions, such as sum, min, and max, accept lists of numbers to operate on. For example, to get the sum of numbers between zero and five, you could do: But remember, anywhere you can use a list, you can use a list comprehension. Say you want to get sum, minimum, and maximum of every number between 0 and 100 that is evenly divisible by 3? No sense typing out a whole list in advance, just use a comprehension:
  • 28. Exception Handling: Many languages have the concept of the “Try-Catch” block. Python uses four keywords: try, except, else, and finally. Code that can possibly throw an exception goes in the try block. except gets the code that runs if an exception is raised. else is an optional block that runs if no exception was raised in the try block, and finally is an optional block of code that will run last, regardless of if an exception was raised. We’ll focus on try and except for this chapter. First, the try clause is executed. If no exception occurs, the except clause is skipped and execution of the try statement is finished. If an exception occurs in the try clause, the rest of the clause is skipped. If the exception’s type matches the exception named after the except keyword, then the except clause is executed. If the exception doesn’t match, then the exception is unhandled and execution stops.
  • 29. The except Clause An except clause may have multiple exceptions, given as a parenthesized tuple: A try statement can also have more than one except clause:
  • 30. Finally Finally, we have finally. finally is an optional block that runs after try, except, and else, regardless of if an exception is thrown or not. This is good for doing any cleanup that you want to happen, whether or not an exception is thrown. As you can see, the Goodbye! gets printed just before the unhandled KeyboardInterrupt gets propagated up and triggers the traceback.