Processing data with Python, using standard library modules you (probably) ne...gjcross
Tutorial #2 from PyCon AU 2012
You have data.
You have Python.
You also have a lot of choices about the best way to work with that data...
Ever wondered when you would use a tuple, list, dictionary, set, ordered dictionary, bucket, queue, counter or named tuple? Phew!
Do you know when to use a loop, iterator or generator to work through a data container?
Why are there so many different "containers" to hold data?
What are the best ways to work with these data containers?
This tutorial will give you all the basics to effectively working with data containers and iterators in Python. Along the way we will cover some very useful modules from the standard library that you may not have used before and will end up wondering how you ever did without them.
This tutorial is aimed at Python beginners. Bring along your laptop so you can interactively work through some of the examples in the tutorial. If you can, install ipython (http://ipython.org/) as we will use it for the demonstrations.
The document discusses container data types in Python, including lists, tuples, sets, and dictionaries.
Lists allow indexing, slicing, and various methods like append(), insert(), pop(), and sort(). Tuples are like lists but immutable, and have methods like count(), index(), and tuple comprehension. Sets store unique elements and support operations like union and intersection. Dictionaries map keys to values and allow accessing elements via keys along with functions like get() and update().
Python Workshop - Learn Python the Hard WayUtkarsh Sengar
This document provides an introduction to learning Python. It discusses prerequisites for Python, basic Python concepts like variables, data types, operators, conditionals and loops. It also covers functions, files, classes and exceptions handling in Python. The document demonstrates these concepts through examples and exercises learners to practice char frequency counting and Caesar cipher encoding/decoding in Python. It encourages learners to practice more to master the language and provides additional learning resources.
Python training slides for beginners that I lecture. Starts from python versions to popular 3 party libraries. Arguments, interactive modes, variable types, language keywords, functions, class etc. If you want to get training please look www.ismailbaydan.com for more details.
The document provides an overview of Python data structures, functions, and recursion. It outlines topics including lists, dictionaries, tuples, sets, functions, recursion, and common errors. The aim is to equip students with a strong foundation in Python programming with a focus on understanding and applying fundamental concepts through programming tasks and examples. Key data structures are explained, such as how to create, access, modify, and delete elements from lists and tuples. Functions are also covered, including defining functions, passing arguments, and common errors.
This document provides an agenda and overview for a Python 3 beginner workshop. The agenda covers topics like numbers, strings, lists, tuples, dictionaries, control statements, functions, classes and in-built functions. For each topic, there are examples provided to demonstrate Python syntax and how to use various features. The workshop is intended to give attendees a hands-on introduction to common Python concepts through examples in the interactive terminal.
Python Cheat Sheet that provides an overview of commonly used Python data structures, functions, and programming concepts. It includes:
- Descriptions and examples of fundamental Python data types like lists, dictionaries, tuples, and sets.
- Explanations of core Python syntax like if/else statements, for loops, functions, and object-oriented programming.
- Examples of built-in functions for working with data structures, like enumerate(), sorted(), zip(), and reversed().
- Demonstrations of syntactic sugar like list/dict/set comprehensions and anonymous lambda functions.
- Notes on strings, modules, exceptions, and other basic programming constructs.
The cheat sheet is intended as
This document provides an overview of Python's basic data types and operations. It discusses numbers, strings, booleans, lists, tuples, and dictionaries. For each type, it demonstrates how to initialize, access, modify, and compare values. Some key points covered include Python's dynamic typing, built-in functions like len() and print(), slicing lists and strings, and unpacking tuples into variables. The document is intended to teach Python fundamentals in a clear and approachable manner.
This document provides an introduction to Python programming. It discusses that Python is an interpretive language and describes advantages like automatic memory management and disadvantages like slower speed compared to compiled languages. It also covers Python versions, the Anaconda IDE, variables and data types, operators, strings, lists, tuples, dictionaries, conditional statements, loops and functions like range(). Examples are provided throughout to demonstrate the core concepts of Python syntax and programming.
This document contains notes from a Python class covering functions, lists, strings, and their methods. It discusses built-in functions like len(), range(), and type conversions. It also covers control flow structures like if/else, for loops, exceptions, modules, and functions in more detail including defining functions, parameters, arguments, returning values, docstring, and variable scopes. Assignments include writing functions to process lists and check for palindromes in strings.
Good morning Salma Hayek you have to do is your purpose of the best time to plant grass seed in the morning Salma Hayek you have to do is your purpose of the best time to plant grass seed in the morning Salma Hayek you have to do is your purpose of the best time to plant grass seed in the morning Salma Hayek you want me potter to plant in spring I will be there in the morning Salma Hayek you have a nice weekend with someone legally allowed in spring a contract for misunderstanding and tomorrow I hope it was about the best msg you want me potter you want me potter you want to do is your purpose of the best time to plant grass seed in the morning Salma Hayek you have to do it up but what do you think about the pros of the morning Salma good mornings are you doing well and tomorrow I hope it goes well and I hope you to do it goes well and tomorrow I have to be there at both locations in spring a nice day service and I hope it goes away soon as I can you have to be to get a I hope it goes away soon I hope it goes away soon I hope it goes away soon as I can you have to be to work at a time I can do is
A for loop is probably the most common type of loop in Python. A for loop will select items from any iterable. In Python an iterable is any container (list, tuple, set, dictionary), as well as many other important objects such as generator function, generator expressions, the results of builtin functions such as filter, map, range and many other items.
The document discusses Python objects and data types. It covers strings, numbers, lists, tuples, and other basic data types in Python. Strings can be indexed and sliced, and operations like concatenation and length calculation can be performed on strings. Lists and tuples are sequence data types that allow ordered collections of elements. Numbers support arithmetic operators and can include integers, floats, complexes, decimals, and rationals.
Python is a programming language developed in 1989 that is still actively developed. It draws influences from languages like Perl, Java, C, C++, and others. Python code is portable, free, and recommended for tasks like system administration scripts, web development, scientific computing, and rapid prototyping. It has a simple syntax and is optionally object-oriented and multi-threaded. Python has extensive libraries for tasks like string manipulation, web programming, databases, and interface design. Popular applications of Python include web development, data analysis, scientific computing, and scripting.
Raspberry Pi - Lecture 5 Python for Raspberry PiMohamed Abdallah
Python syntax, Strings and console output, Conditional an, control flow, Functions, Lists and dictionaries, Loops, Bitwise operators, Classes, File Input/output
Python 101++: Let's Get Down to Business!Paige Bailey
You've started the Codecademy and Coursera courses; you've thumbed through Zed Shaw's "Learn Python the Hard Way"; and now you're itching to see what Python can help you do. This is the workshop for you!
Here's the breakdown: we're going to be taking you on a whirlwind tour of Python's capabilities. By the end of the workshop, you should be able to easily follow any of the widely available Python courses on the internet, and have a grasp on some of the more complex aspects of the language.
Please don't forget to bring your personal laptop!
Audience: This course is aimed at those who already have some basic programming experience, either in Python or in another high level programming language (such as C/C++, Fortran, Java, Ruby, Perl, or Visual Basic). If you're an absolute beginner -- new to Python, and new to programming in general -- make sure to check out the "Python 101" workshop!
Python is an open source, highly interactive, object oriented, interpreted, easy programming language powered by Python Software Foundation PSF. It can be easily integrated to various IT fields such as web application programming, automation scripting, data science, machine learning, mathematical computing
METHODS DESCRIPTION
copy() They copy() method returns a shallow copy of the dictionary.
clear() The clear() method removes all items from the dictionary.
pop() Removes and returns an element from a dictionary having the given key.
popitem() Removes the arbitrary key-value pair from the dictionary and returns it as tuple.
get() It is a conventional method to access a value for a key.
dictionary_name.values() returns a list of all the values available in a given dictionary.
str() Produces a printable string representation of a dictionary.
update() Adds dictionary dict2’s key-values pairs to dict
setdefault() Set dict[key]=default if key is not already in dict
keys() Returns list of dictionary dict’s keys
items() Returns a list of dict’s (key, value) tuple pairs
has_key() Returns true if key in dictionary dict, false otherwise
fromkeys() Create a new dictionary with keys from seq and values set to value.
type() Returns the type of the passed variable.
cmp() Compares elements of both dict.
This document provides an overview of the Python programming language. It discusses Python's history and design, data types like integers, floats, strings, lists, tuples and dictionaries. It also covers core concepts like variables, expressions, control flow with if/else statements and loops. The document demonstrates how to take user input, read and write files, and describes moving Python code to files to make it reusable.
This document provides an agenda and overview for a Python tutorial presented over multiple sessions. The first session introduces Python and demonstrates how to use the Python interpreter. The second session covers basic Python data structures like lists, modules, input/output, and exceptions. An optional third session discusses unit testing. The document explains that Python is an easy to learn yet powerful programming language that supports object-oriented programming and high-level data structures in an interpreted, dynamic environment.
AI Agents in Logistics and Supply Chain Applications Benefits and ImplementationChristine Shepherd
AI agents are reshaping logistics and supply chain operations by enabling automation, predictive insights, and real-time decision-making across key functions such as demand forecasting, inventory management, procurement, transportation, and warehouse operations. Powered by technologies like machine learning, NLP, computer vision, and robotic process automation, these agents deliver significant benefits including cost reduction, improved efficiency, greater visibility, and enhanced adaptability to market changes. While practical use cases show measurable gains in areas like dynamic routing and real-time inventory tracking, successful implementation requires careful integration with existing systems, quality data, and strategic scaling. Despite challenges such as data integration and change management, AI agents offer a strong competitive edge, with widespread industry adoption expected by 2025.
More Related Content
Similar to Advanced Python after beginner python for intermediate learners (20)
Python Cheat Sheet that provides an overview of commonly used Python data structures, functions, and programming concepts. It includes:
- Descriptions and examples of fundamental Python data types like lists, dictionaries, tuples, and sets.
- Explanations of core Python syntax like if/else statements, for loops, functions, and object-oriented programming.
- Examples of built-in functions for working with data structures, like enumerate(), sorted(), zip(), and reversed().
- Demonstrations of syntactic sugar like list/dict/set comprehensions and anonymous lambda functions.
- Notes on strings, modules, exceptions, and other basic programming constructs.
The cheat sheet is intended as
This document provides an overview of Python's basic data types and operations. It discusses numbers, strings, booleans, lists, tuples, and dictionaries. For each type, it demonstrates how to initialize, access, modify, and compare values. Some key points covered include Python's dynamic typing, built-in functions like len() and print(), slicing lists and strings, and unpacking tuples into variables. The document is intended to teach Python fundamentals in a clear and approachable manner.
This document provides an introduction to Python programming. It discusses that Python is an interpretive language and describes advantages like automatic memory management and disadvantages like slower speed compared to compiled languages. It also covers Python versions, the Anaconda IDE, variables and data types, operators, strings, lists, tuples, dictionaries, conditional statements, loops and functions like range(). Examples are provided throughout to demonstrate the core concepts of Python syntax and programming.
This document contains notes from a Python class covering functions, lists, strings, and their methods. It discusses built-in functions like len(), range(), and type conversions. It also covers control flow structures like if/else, for loops, exceptions, modules, and functions in more detail including defining functions, parameters, arguments, returning values, docstring, and variable scopes. Assignments include writing functions to process lists and check for palindromes in strings.
Good morning Salma Hayek you have to do is your purpose of the best time to plant grass seed in the morning Salma Hayek you have to do is your purpose of the best time to plant grass seed in the morning Salma Hayek you have to do is your purpose of the best time to plant grass seed in the morning Salma Hayek you want me potter to plant in spring I will be there in the morning Salma Hayek you have a nice weekend with someone legally allowed in spring a contract for misunderstanding and tomorrow I hope it was about the best msg you want me potter you want me potter you want to do is your purpose of the best time to plant grass seed in the morning Salma Hayek you have to do it up but what do you think about the pros of the morning Salma good mornings are you doing well and tomorrow I hope it goes well and I hope you to do it goes well and tomorrow I have to be there at both locations in spring a nice day service and I hope it goes away soon as I can you have to be to get a I hope it goes away soon I hope it goes away soon I hope it goes away soon as I can you have to be to work at a time I can do is
A for loop is probably the most common type of loop in Python. A for loop will select items from any iterable. In Python an iterable is any container (list, tuple, set, dictionary), as well as many other important objects such as generator function, generator expressions, the results of builtin functions such as filter, map, range and many other items.
The document discusses Python objects and data types. It covers strings, numbers, lists, tuples, and other basic data types in Python. Strings can be indexed and sliced, and operations like concatenation and length calculation can be performed on strings. Lists and tuples are sequence data types that allow ordered collections of elements. Numbers support arithmetic operators and can include integers, floats, complexes, decimals, and rationals.
Python is a programming language developed in 1989 that is still actively developed. It draws influences from languages like Perl, Java, C, C++, and others. Python code is portable, free, and recommended for tasks like system administration scripts, web development, scientific computing, and rapid prototyping. It has a simple syntax and is optionally object-oriented and multi-threaded. Python has extensive libraries for tasks like string manipulation, web programming, databases, and interface design. Popular applications of Python include web development, data analysis, scientific computing, and scripting.
Raspberry Pi - Lecture 5 Python for Raspberry PiMohamed Abdallah
Python syntax, Strings and console output, Conditional an, control flow, Functions, Lists and dictionaries, Loops, Bitwise operators, Classes, File Input/output
Python 101++: Let's Get Down to Business!Paige Bailey
You've started the Codecademy and Coursera courses; you've thumbed through Zed Shaw's "Learn Python the Hard Way"; and now you're itching to see what Python can help you do. This is the workshop for you!
Here's the breakdown: we're going to be taking you on a whirlwind tour of Python's capabilities. By the end of the workshop, you should be able to easily follow any of the widely available Python courses on the internet, and have a grasp on some of the more complex aspects of the language.
Please don't forget to bring your personal laptop!
Audience: This course is aimed at those who already have some basic programming experience, either in Python or in another high level programming language (such as C/C++, Fortran, Java, Ruby, Perl, or Visual Basic). If you're an absolute beginner -- new to Python, and new to programming in general -- make sure to check out the "Python 101" workshop!
Python is an open source, highly interactive, object oriented, interpreted, easy programming language powered by Python Software Foundation PSF. It can be easily integrated to various IT fields such as web application programming, automation scripting, data science, machine learning, mathematical computing
METHODS DESCRIPTION
copy() They copy() method returns a shallow copy of the dictionary.
clear() The clear() method removes all items from the dictionary.
pop() Removes and returns an element from a dictionary having the given key.
popitem() Removes the arbitrary key-value pair from the dictionary and returns it as tuple.
get() It is a conventional method to access a value for a key.
dictionary_name.values() returns a list of all the values available in a given dictionary.
str() Produces a printable string representation of a dictionary.
update() Adds dictionary dict2’s key-values pairs to dict
setdefault() Set dict[key]=default if key is not already in dict
keys() Returns list of dictionary dict’s keys
items() Returns a list of dict’s (key, value) tuple pairs
has_key() Returns true if key in dictionary dict, false otherwise
fromkeys() Create a new dictionary with keys from seq and values set to value.
type() Returns the type of the passed variable.
cmp() Compares elements of both dict.
This document provides an overview of the Python programming language. It discusses Python's history and design, data types like integers, floats, strings, lists, tuples and dictionaries. It also covers core concepts like variables, expressions, control flow with if/else statements and loops. The document demonstrates how to take user input, read and write files, and describes moving Python code to files to make it reusable.
This document provides an agenda and overview for a Python tutorial presented over multiple sessions. The first session introduces Python and demonstrates how to use the Python interpreter. The second session covers basic Python data structures like lists, modules, input/output, and exceptions. An optional third session discusses unit testing. The document explains that Python is an easy to learn yet powerful programming language that supports object-oriented programming and high-level data structures in an interpreted, dynamic environment.
AI Agents in Logistics and Supply Chain Applications Benefits and ImplementationChristine Shepherd
AI agents are reshaping logistics and supply chain operations by enabling automation, predictive insights, and real-time decision-making across key functions such as demand forecasting, inventory management, procurement, transportation, and warehouse operations. Powered by technologies like machine learning, NLP, computer vision, and robotic process automation, these agents deliver significant benefits including cost reduction, improved efficiency, greater visibility, and enhanced adaptability to market changes. While practical use cases show measurable gains in areas like dynamic routing and real-time inventory tracking, successful implementation requires careful integration with existing systems, quality data, and strategic scaling. Despite challenges such as data integration and change management, AI agents offer a strong competitive edge, with widespread industry adoption expected by 2025.
Kubernetes Security Act Now Before It’s Too LateMichael Furman
In today's cloud-native landscape, Kubernetes has become the de facto standard for orchestrating containerized applications, but its inherent complexity introduces unique security challenges. Are you one YAML away from disaster?
This presentation, "Kubernetes Security: Act Now Before It’s Too Late," is your essential guide to understanding and mitigating the critical security risks within your Kubernetes environments. This presentation dives deep into the OWASP Kubernetes Top Ten, providing actionable insights to harden your clusters.
We will cover:
The fundamental architecture of Kubernetes and why its security is paramount.
In-depth strategies for protecting your Kubernetes Control Plane, including kube-apiserver and etcd.
Crucial best practices for securing your workloads and nodes, covering topics like privileged containers, root filesystem security, and the essential role of Pod Security Admission.
Don't wait for a breach. Learn how to identify, prevent, and respond to Kubernetes security threats effectively.
It's time to act now before it's too late!
Mastering AI Workflows with FME - Peak of Data & AI 2025Safe Software
Harness the full potential of AI with FME: From creating high-quality training data to optimizing models and utilizing results, FME supports every step of your AI workflow. Seamlessly integrate a wide range of models, including those for data enhancement, forecasting, image and object recognition, and large language models. Customize AI models to meet your exact needs with FME’s powerful tools for training, optimization, and seamless integration
Providing an OGC API Processes REST Interface for FME FlowSafe Software
This presentation will showcase an adapter for FME Flow that provides REST endpoints for FME Workspaces following the OGC API Processes specification. The implementation delivers robust, user-friendly API endpoints, including standardized methods for parameter provision. Additionally, it enhances security and user management by supporting OAuth2 authentication. Join us to discover how these advancements can elevate your enterprise integration workflows and ensure seamless, secure interactions with FME Flow.
Presentation given at the LangChain community meetup London
https://lu.ma/9d5fntgj
Coveres
Agentic AI: Beyond the Buzz
Introduction to AI Agent and Agentic AI
Agent Use case and stats
Introduction to LangGraph
Build agent with LangGraph Studio V2
➡ 🌍📱👉COPY & PASTE LINK👉👉👉 ➤ ➤➤ https://drfiles.net/
Wondershare Filmora Crack is a user-friendly video editing software designed for both beginners and experienced users.
Your startup on AWS - How to architect and maintain a Lean and Mean accountangelo60207
Prevent infrastructure costs from becoming a significant line item on your startup’s budget! Serial entrepreneur and software architect Angelo Mandato will share his experience with AWS Activate (startup credits from AWS) and knowledge on how to architect a lean and mean AWS account ideal for budget minded and bootstrapped startups. In this session you will learn how to manage a production ready AWS account capable of scaling as your startup grows for less than $100/month before credits. We will discuss AWS Budgets, Cost Explorer, architect priorities, and the importance of having flexible, optimized Infrastructure as Code. We will wrap everything up discussing opportunities where to save with AWS services such as S3, EC2, Load Balancers, Lambda Functions, RDS, and many others.
This OrionX's 14th semi-annual report on the state of the cryptocurrency mining market. The report focuses on Proof-of-Work cryptocurrencies since those use substantial supercomputer power to mint new coins and encode transactions on their blockchains. Only two make the cut this time, Bitcoin with $18 billion of annual economic value produced and Dogecoin with $1 billion. Bitcoin has now reached the Zettascale with typical hash rates of 0.9 Zettahashes per second. Bitcoin is powered by the world's largest decentralized supercomputer in a continuous winner take all lottery incentive network.
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdfRejig Digital
Unlock the future of oil & gas safety with advanced environmental detection technologies that transform hazard monitoring and risk management. This presentation explores cutting-edge innovations that enhance workplace safety, protect critical assets, and ensure regulatory compliance in high-risk environments.
🔍 What You’ll Learn:
✅ How advanced sensors detect environmental threats in real-time for proactive hazard prevention
🔧 Integration of IoT and AI to enable rapid response and minimize incident impact
📡 Enhancing workforce protection through continuous monitoring and data-driven safety protocols
💡 Case studies highlighting successful deployment of environmental detection systems in oil & gas operations
Ideal for safety managers, operations leaders, and technology innovators in the oil & gas industry, this presentation offers practical insights and strategies to revolutionize safety standards and boost operational resilience.
👉 Learn more: https://www.rejigdigital.com/blog/continuous-monitoring-prevent-blowouts-well-control-issues/
Interested in leveling up your JavaScript skills? Join us for our Introduction to TypeScript workshop.
Learn how TypeScript can improve your code with dynamic typing, better tooling, and cleaner architecture. Whether you're a beginner or have some experience with JavaScript, this session will give you a solid foundation in TypeScript and how to integrate it into your projects.
Workshop content:
- What is TypeScript?
- What is the problem with JavaScript?
- Why TypeScript is the solution
- Coding demo
Enabling BIM / GIS integrations with Other Systems with FMESafe Software
Jacobs has successfully utilized FME to tackle the complexities of integrating diverse data sources in a confidential $1 billion campus improvement project. The project aimed to create a comprehensive digital twin by merging Building Information Modeling (BIM) data, Construction Operations Building Information Exchange (COBie) data, and various other data sources into a unified Geographic Information System (GIS) platform. The challenge lay in the disparate nature of these data sources, which were siloed and incompatible with each other, hindering efficient data management and decision-making processes.
To address this, Jacobs leveraged FME to automate the extraction, transformation, and loading (ETL) of data between ArcGIS Indoors and IBM Maximo. This process ensured accurate transfer of maintainable asset and work order data, creating a comprehensive 2D and 3D representation of the campus for Facility Management. FME's server capabilities enabled real-time updates and synchronization between ArcGIS Indoors and Maximo, facilitating automatic updates of asset information and work orders. Additionally, Survey123 forms allowed field personnel to capture and submit data directly from their mobile devices, triggering FME workflows via webhooks for real-time data updates. This seamless integration has significantly enhanced data management, improved decision-making processes, and ensured data consistency across the project lifecycle.
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdfAlkin Tezuysal
As the demand for vector databases and Generative AI continues to rise, integrating vector storage and search capabilities into traditional databases has become increasingly important. This session introduces the *MyVector Plugin*, a project that brings native vector storage and similarity search to MySQL. Unlike PostgreSQL, which offers interfaces for adding new data types and index methods, MySQL lacks such extensibility. However, by utilizing MySQL's server component plugin and UDF, the *MyVector Plugin* successfully adds a fully functional vector search feature within the existing MySQL + InnoDB infrastructure, eliminating the need for a separate vector database. The session explains the technical aspects of integrating vector support into MySQL, the challenges posed by its architecture, and real-world use cases that showcase the advantages of combining vector search with MySQL's robust features. Attendees will leave with practical insights on how to add vector search capabilities to their MySQL systems.
מכונת קנטים המתאימה לנגריות קטנות או גדולות (כמכונת גיבוי).
מדביקה קנטים מגליל או פסים, עד עובי קנט – 3 מ"מ ועובי חומר עד 40 מ"מ. בקר ממוחשב המתריע על תקלות, ומנועים מאסיביים תעשייתיים כמו במכונות הגדולות.
Artificial Intelligence in the Nonprofit Boardroom.pdfOnBoard
OnBoard recently partnered with Microsoft Tech for Social Impact on the AI in the Nonprofit Boardroom Survey, an initiative designed to uncover the current and future role of artificial intelligence in nonprofit governance.
Artificial Intelligence in the Nonprofit Boardroom.pdfOnBoard
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.
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.
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.
*******************************************************************
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.