This document provides a cheat sheet on Python keywords and basic data types. It lists common Python keywords like False, True, and, or, not, break, continue, class, def, if, else, for, while, in, is, None, lambda, and return along with code examples. It also covers basic data types like Boolean, integer, float, string, list, set, dictionary, and complex data types like classes. It provides examples of using lists, sets, dictionaries, classes and functions in Python.
This document provides examples and descriptions of Python keywords and basic data types. It discusses keywords like False, True, and, or, not, break, continue, class, def, if, elif, else, for, while, in, is, None, lambda, and return. It also covers basic data types like integers, floats, strings, lists, sets, dictionaries, and Boolean values. It provides code examples to demonstrate the usage of these keywords and data types in Python.
Here are the steps to solve this problem:
1. Convert both lists of numbers to sets:
set1 = {11, 2, 3, 4, 15, 6, 7, 8, 9, 10}
set2 = {15, 2, 3, 4, 15, 6}
2. Find the intersection of the two sets:
intersection = set1.intersection(set2)
3. The number of elements in the intersection is the number of similar elements:
similarity = len(intersection)
4. Print the result:
print(similarity)
The similarity between the two sets is 4, since they both contain the elements {2, 3, 4, 15}.
File handling in Python allows programs to read from and write to files stored on the file system. There are different modes for opening files, such as read ("r"), write ("w"), and append ("a"). Common file operations include reading, writing, updating, deleting, and creating files. Files can be opened, read from and written to, then closed. Python supports various data types that can be read from or written to files, such as text, binary, images, and audio files. File handling is an important part of building applications that need to persist data.
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 discusses lists and dictionaries in Python. It provides definitions and examples of lists, including how to add and remove elements from lists. It also discusses sorting lists and getting the length of lists. Examples are provided for integrating lists with loops. The document then discusses dictionaries, including how to represent them and retrieve values from dictionaries using keys. Examples are provided for using loops to print keys and values from dictionaries. It also discusses modules like NumPy and Pandas that can be imported in Python.
Lists, tuples, and dictionaries are common data structures in Python. Lists are mutable sequences that are defined using square brackets. Tuples are immutable sequences defined using parentheses. Dictionaries store key-value pairs within curly braces, with unique keys. These data structures support operations like indexing, slicing, length checking, membership testing, and iteration.
This document provides an introduction to Python for high school programmers. It covers background information on Python, key concepts like data types and operators, and basics of the language like variables, collections, control flow, and object-oriented programming. Code examples are included to demonstrate various features. The presentation aims to get students started with Python and provide an overview of what it can do.
This document discusses lists in Python. It covers:
- Creating lists of different data types like numbers, strings, and mixed types
- Accessing list elements using indexes and slices
- Common list methods like append(), insert(), remove(), pop(), sort(), reverse()
- Joining and extending lists
- Examples of using lists and conditional statements
The basics of Python are rather straightforward. In a few minutes you can learn most of the syntax. There are some gotchas along the way that might appear tricky. This talk is meant to bring programmers up to speed with Python. They should be able to read and write Python.
This document provides an overview of the Python programming language. It includes several code examples and summaries of key Python concepts like strings, lists, tuples, dictionaries, files, regular expressions, and object-oriented programming. It also lists some common Python functions and modules for tasks like HTTP requests and database access. The document aims to introduce Python's main features and provide basic code samples to help new Python learners.
This document provides an overview and introduction to Python programming. It covers setting up Python, background on the language, basic syntax like printing, variables, operators, control structures, functions, and data structures. It encourages participation and practicing the concepts by following along. The goal is to teach the fundamentals of Python in an interactive class format.
Python Programming for basic beginners.pptxmohitesoham12
The document provides an overview of Python programming concepts including data types, variables, operators, and collections like lists and tuples. It defines Python as a general purpose programming language created in 1991 that can be used for desktop, web, machine learning, and data science apps. Key data types covered include numbers, strings, lists, and tuples. Operators for arithmetic, comparison, logical, membership, and identity are also summarized. Various list and tuple methods for accessing, modifying, sorting, and joining their items are demonstrated through examples.
This document provides a 5 minute summary of key Python concepts including variables, data types, conditionals, loops, functions, classes and modules. It demonstrates how to define and use integers, floats, strings, booleans, lists, tuples, dictionaries and sets. It also shows the syntax for if/else statements, for/while loops, functions, lambda functions, classes and importing/using modules in Python.
This document provides an overview of many common Python programming concepts including variables, strings, lists, tuples, dictionaries, conditionals, functions, classes, files and exceptions. It demonstrates how to store and manipulate different data types, write conditional logic, define reusable blocks of code as functions, organize code into classes and objects, read from and write to files, and handle errors through exceptions. Key examples include creating and accessing elements in lists and dictionaries, writing conditional statements, defining and calling functions, creating classes and using inheritance, opening and reading/writing files, and using try/except blocks to catch errors.
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.
This document summarizes Python basics including its features, popularity in different fields and companies, data types, control flow, containers like lists and dictionaries, NumPy for numerical computing, and classes. Python is an interpreted, general-purpose language with rich library support. It is commonly used in computer science, data analysis, biology, and academic communities. Major companies like Google, Dropbox, and Instagram use Python.
This document summarizes Python basics including its features, popularity in different fields and companies, data types, control flow, containers like lists and dictionaries, NumPy for numerical computing, and classes. Python is an interpreted, general-purpose language with rich library support. It is commonly used in computer science, data analysis, biology, and academic communities. Major companies like Google, Dropbox, and Instagram use Python.
This document provides a summary of the main data types in Python including text, numeric, sequence, mapping, set, boolean, and binary types. It discusses the main characteristics of integers, floats, complexes, strings, lists, tuples, dictionaries, and sets. It covers how to define, access, modify, loop through and add/remove items for each data type. The key details covered include slicing strings, converting between types, appending/inserting/removing list items, immutable tuples, unordered sets and indexed dictionaries.
This document provides an overview of Python lists:
- Lists store a series of items in a particular order and allow you to access items using an index or loop through the items.
- You can add and remove items from lists, sort lists, loop through lists to print or modify items, and access items by index.
- Common list operations include appending to add an item, inserting to add an item at a specific index, removing items, sorting lists, finding the length of a list, and accessing items by index.
The document provides an overview of common Python data structures and programming concepts including:
- Strings, variables, and concatenation for combining strings
- Lists for storing ordered sets of items that can be accessed by index or looped through
- Tuples for storing immutable sets of items similar to lists
- Dictionaries for storing connections between keys and values in non-ordered key-value pairs
- Common operations for each like appending, inserting, removing, sorting, and slicing items
It also covers conditional statements, functions, files, exceptions, classes and objects, user input/output, and while and for loops for iteration. The goal is to introduce fundamental Python programming concepts and data handling techniques.
The document provides an overview of common Python data structures and programming concepts including:
- Strings, variables, and concatenation for combining strings
- Lists for storing ordered sets of items that can be accessed by index or looped through
- Tuples for storing immutable sets of items similar to lists
- Dictionaries for storing connections between keys and values in non-ordered key-value pairs
- Common operations for each like appending, inserting, removing, sorting, and slicing items
It also covers conditional statements, functions, files, exceptions, classes and objects, user input/output, and while and for loops for iteration. The goal is to introduce fundamental Python programming concepts and data structures.
This document provides an overview of Python lists:
- Lists store a series of items in a particular order and allow you to access items using an index or loop through the items.
- You can add and remove items from lists, sort lists, loop through lists to print or modify items, and access items by index.
- Common list operations include appending items, inserting items, removing items, sorting lists, finding the length of a list, and accessing items by index. Lists provide a powerful way to organize and work with sets of data in Python.
Learn about the APGAR SCORE , a simple yet effective method to evaluate a newborn's physical condition immediately after birth ....this presentation covers .....
what is apgar score ?
Components of apgar score.
Scoring system
Indications of apgar score........
How to Configure Scheduled Actions in odoo 18Celine George
Scheduled actions in Odoo 18 automate tasks by running specific operations at set intervals. These background processes help streamline workflows, such as updating data, sending reminders, or performing routine tasks, ensuring smooth and efficient system operations.
Ad
More Related Content
Similar to cover every basics of python with this.. (20)
This document discusses lists in Python. It covers:
- Creating lists of different data types like numbers, strings, and mixed types
- Accessing list elements using indexes and slices
- Common list methods like append(), insert(), remove(), pop(), sort(), reverse()
- Joining and extending lists
- Examples of using lists and conditional statements
The basics of Python are rather straightforward. In a few minutes you can learn most of the syntax. There are some gotchas along the way that might appear tricky. This talk is meant to bring programmers up to speed with Python. They should be able to read and write Python.
This document provides an overview of the Python programming language. It includes several code examples and summaries of key Python concepts like strings, lists, tuples, dictionaries, files, regular expressions, and object-oriented programming. It also lists some common Python functions and modules for tasks like HTTP requests and database access. The document aims to introduce Python's main features and provide basic code samples to help new Python learners.
This document provides an overview and introduction to Python programming. It covers setting up Python, background on the language, basic syntax like printing, variables, operators, control structures, functions, and data structures. It encourages participation and practicing the concepts by following along. The goal is to teach the fundamentals of Python in an interactive class format.
Python Programming for basic beginners.pptxmohitesoham12
The document provides an overview of Python programming concepts including data types, variables, operators, and collections like lists and tuples. It defines Python as a general purpose programming language created in 1991 that can be used for desktop, web, machine learning, and data science apps. Key data types covered include numbers, strings, lists, and tuples. Operators for arithmetic, comparison, logical, membership, and identity are also summarized. Various list and tuple methods for accessing, modifying, sorting, and joining their items are demonstrated through examples.
This document provides a 5 minute summary of key Python concepts including variables, data types, conditionals, loops, functions, classes and modules. It demonstrates how to define and use integers, floats, strings, booleans, lists, tuples, dictionaries and sets. It also shows the syntax for if/else statements, for/while loops, functions, lambda functions, classes and importing/using modules in Python.
This document provides an overview of many common Python programming concepts including variables, strings, lists, tuples, dictionaries, conditionals, functions, classes, files and exceptions. It demonstrates how to store and manipulate different data types, write conditional logic, define reusable blocks of code as functions, organize code into classes and objects, read from and write to files, and handle errors through exceptions. Key examples include creating and accessing elements in lists and dictionaries, writing conditional statements, defining and calling functions, creating classes and using inheritance, opening and reading/writing files, and using try/except blocks to catch errors.
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.
This document summarizes Python basics including its features, popularity in different fields and companies, data types, control flow, containers like lists and dictionaries, NumPy for numerical computing, and classes. Python is an interpreted, general-purpose language with rich library support. It is commonly used in computer science, data analysis, biology, and academic communities. Major companies like Google, Dropbox, and Instagram use Python.
This document summarizes Python basics including its features, popularity in different fields and companies, data types, control flow, containers like lists and dictionaries, NumPy for numerical computing, and classes. Python is an interpreted, general-purpose language with rich library support. It is commonly used in computer science, data analysis, biology, and academic communities. Major companies like Google, Dropbox, and Instagram use Python.
This document provides a summary of the main data types in Python including text, numeric, sequence, mapping, set, boolean, and binary types. It discusses the main characteristics of integers, floats, complexes, strings, lists, tuples, dictionaries, and sets. It covers how to define, access, modify, loop through and add/remove items for each data type. The key details covered include slicing strings, converting between types, appending/inserting/removing list items, immutable tuples, unordered sets and indexed dictionaries.
This document provides an overview of Python lists:
- Lists store a series of items in a particular order and allow you to access items using an index or loop through the items.
- You can add and remove items from lists, sort lists, loop through lists to print or modify items, and access items by index.
- Common list operations include appending to add an item, inserting to add an item at a specific index, removing items, sorting lists, finding the length of a list, and accessing items by index.
The document provides an overview of common Python data structures and programming concepts including:
- Strings, variables, and concatenation for combining strings
- Lists for storing ordered sets of items that can be accessed by index or looped through
- Tuples for storing immutable sets of items similar to lists
- Dictionaries for storing connections between keys and values in non-ordered key-value pairs
- Common operations for each like appending, inserting, removing, sorting, and slicing items
It also covers conditional statements, functions, files, exceptions, classes and objects, user input/output, and while and for loops for iteration. The goal is to introduce fundamental Python programming concepts and data handling techniques.
The document provides an overview of common Python data structures and programming concepts including:
- Strings, variables, and concatenation for combining strings
- Lists for storing ordered sets of items that can be accessed by index or looped through
- Tuples for storing immutable sets of items similar to lists
- Dictionaries for storing connections between keys and values in non-ordered key-value pairs
- Common operations for each like appending, inserting, removing, sorting, and slicing items
It also covers conditional statements, functions, files, exceptions, classes and objects, user input/output, and while and for loops for iteration. The goal is to introduce fundamental Python programming concepts and data structures.
This document provides an overview of Python lists:
- Lists store a series of items in a particular order and allow you to access items using an index or loop through the items.
- You can add and remove items from lists, sort lists, loop through lists to print or modify items, and access items by index.
- Common list operations include appending items, inserting items, removing items, sorting lists, finding the length of a list, and accessing items by index. Lists provide a powerful way to organize and work with sets of data in Python.
Learn about the APGAR SCORE , a simple yet effective method to evaluate a newborn's physical condition immediately after birth ....this presentation covers .....
what is apgar score ?
Components of apgar score.
Scoring system
Indications of apgar score........
How to Configure Scheduled Actions in odoo 18Celine George
Scheduled actions in Odoo 18 automate tasks by running specific operations at set intervals. These background processes help streamline workflows, such as updating data, sending reminders, or performing routine tasks, ensuring smooth and efficient system operations.
What is the Philosophy of Statistics? (and how I was drawn to it)jemille6
What is the Philosophy of Statistics? (and how I was drawn to it)
Deborah G Mayo
At Dept of Philosophy, Virginia Tech
April 30, 2025
ABSTRACT: I give an introductory discussion of two key philosophical controversies in statistics in relation to today’s "replication crisis" in science: the role of probability, and the nature of evidence, in error-prone inference. I begin with a simple principle: We don’t have evidence for a claim C if little, if anything, has been done that would have found C false (or specifically flawed), even if it is. Along the way, I’ll sprinkle in some autobiographical reflections.
Link your Lead Opportunities into Spreadsheet using odoo CRMCeline George
In Odoo 17 CRM, linking leads and opportunities to a spreadsheet can be done by exporting data or using Odoo’s built-in spreadsheet integration. To export, navigate to the CRM app, filter and select the relevant records, and then export the data in formats like CSV or XLSX, which can be opened in external spreadsheet tools such as Excel or Google Sheets.
A measles outbreak originating in West Texas has been linked to confirmed cases in New Mexico, with additional cases reported in Oklahoma and Kansas. The current case count is 817 from Texas, New Mexico, Oklahoma, and Kansas. 97 individuals have required hospitalization, and 3 deaths, 2 children in Texas and one adult in New Mexico. These fatalities mark the first measles-related deaths in the United States since 2015 and the first pediatric measles death since 2003.
The YSPH Virtual Medical Operations Center Briefs (VMOC) were created as a service-learning project by faculty and graduate students at the Yale School of Public Health in response to the 2010 Haiti Earthquake. Each year, the VMOC Briefs are produced by students enrolled in Environmental Health Science Course 581 - Public Health Emergencies: Disaster Planning and Response. These briefs compile diverse information sources – including status reports, maps, news articles, and web content– into a single, easily digestible document that can be widely shared and used interactively. Key features of this report include:
- Comprehensive Overview: Provides situation updates, maps, relevant news, and web resources.
- Accessibility: Designed for easy reading, wide distribution, and interactive use.
- Collaboration: The “unlocked" format enables other responders to share, copy, and adapt seamlessly. The students learn by doing, quickly discovering how and where to find critical information and presenting it in an easily understood manner.
CURRENT CASE COUNT: 817 (As of 05/3/2025)
• Texas: 688 (+20)(62% of these cases are in Gaines County).
• New Mexico: 67 (+1 )(92.4% of the cases are from Eddy County)
• Oklahoma: 16 (+1)
• Kansas: 46 (32% of the cases are from Gray County)
HOSPITALIZATIONS: 97 (+2)
• Texas: 89 (+2) - This is 13.02% of all TX cases.
• New Mexico: 7 - This is 10.6% of all NM cases.
• Kansas: 1 - This is 2.7% of all KS cases.
DEATHS: 3
• Texas: 2 – This is 0.31% of all cases
• New Mexico: 1 – This is 1.54% of all cases
US NATIONAL CASE COUNT: 967 (Confirmed and suspected):
INTERNATIONAL SPREAD (As of 4/2/2025)
• Mexico – 865 (+58)
‒Chihuahua, Mexico: 844 (+58) cases, 3 hospitalizations, 1 fatality
• Canada: 1531 (+270) (This reflects Ontario's Outbreak, which began 11/24)
‒Ontario, Canada – 1243 (+223) cases, 84 hospitalizations.
• Europe: 6,814
Redesigning Education as a Cognitive Ecosystem: Practical Insights into Emerg...Leonel Morgado
Slides used at the Invited Talk at the Harvard - Education University of Hong Kong - Stanford Joint Symposium, "Emerging Technologies and Future Talents", 2025-05-10, Hong Kong, China.
The insect cuticle is a tough, external exoskeleton composed of chitin and proteins, providing protection and support. However, as insects grow, they need to shed this cuticle periodically through a process called moulting. During moulting, a new cuticle is prepared underneath, and the old one is shed, allowing the insect to grow, repair damaged cuticle, and change form. This process is crucial for insect development and growth, enabling them to transition from one stage to another, such as from larva to pupa or adult.
How to Manage Purchase Alternatives in Odoo 18Celine George
Managing purchase alternatives is crucial for ensuring a smooth and cost-effective procurement process. Odoo 18 provides robust tools to handle alternative vendors and products, enabling businesses to maintain flexibility and mitigate supply chain disruptions.
Happy May and Happy Weekend, My Guest Students.
Weekends seem more popular for Workshop Class Days lol.
These Presentations are timeless. Tune in anytime, any weekend.
<<I am Adult EDU Vocational, Ordained, Certified and Experienced. Course genres are personal development for holistic health, healing, and self care. I am also skilled in Health Sciences. However; I am not coaching at this time.>>
A 5th FREE WORKSHOP/ Daily Living.
Our Sponsor / Learning On Alison:
Sponsor: Learning On Alison:
— We believe that empowering yourself shouldn’t just be rewarding, but also really simple (and free). That’s why your journey from clicking on a course you want to take to completing it and getting a certificate takes only 6 steps.
Hopefully Before Summer, We can add our courses to the teacher/creator section. It's all within project management and preps right now. So wish us luck.
Check our Website for more info: https://ldmchapels.weebly.com
Get started for Free.
Currency is Euro. Courses can be free unlimited. Only pay for your diploma. See Website for xtra assistance.
Make sure to convert your cash. Online Wallets do vary. I keep my transactions safe as possible. I do prefer PayPal Biz. (See Site for more info.)
Understanding Vibrations
If not experienced, it may seem weird understanding vibes? We start small and by accident. Usually, we learn about vibrations within social. Examples are: That bad vibe you felt. Also, that good feeling you had. These are common situations we often have naturally. We chit chat about it then let it go. However; those are called vibes using your instincts. Then, your senses are called your intuition. We all can develop the gift of intuition and using energy awareness.
Energy Healing
First, Energy healing is universal. This is also true for Reiki as an art and rehab resource. Within the Health Sciences, Rehab has changed dramatically. The term is now very flexible.
Reiki alone, expanded tremendously during the past 3 years. Distant healing is almost more popular than one-on-one sessions? It’s not a replacement by all means. However, its now easier access online vs local sessions. This does break limit barriers providing instant comfort.
Practice Poses
You can stand within mountain pose Tadasana to get started.
Also, you can start within a lotus Sitting Position to begin a session.
There’s no wrong or right way. Maybe if you are rushing, that’s incorrect lol. The key is being comfortable, calm, at peace. This begins any session.
Also using props like candles, incenses, even going outdoors for fresh air.
(See Presentation for all sections, THX)
Clearing Karma, Letting go.
Now, that you understand more about energies, vibrations, the practice fusions, let’s go deeper. I wanted to make sure you all were comfortable. These sessions are for all levels from beginner to review.
Again See the presentation slides, Thx.
In this concise presentation, Dr. G.S. Virdi (Former Chief Scientist, CSIR-CEERI, Pilani) introduces the Junction Field-Effect Transistor (JFET)—a cornerstone of modern analog electronics. You’ll discover:
Why JFETs? Learn how their high input impedance and low noise solve the drawbacks of bipolar transistors.
JFET vs. MOSFET: Understand the core differences between JFET and MOSFET devices.
Internal Structure: See how source, drain, gate, and the depletion region form a controllable semiconductor channel.
Real-World Applications: Explore where JFETs power amplifiers, sensors, and precision circuits.
Perfect for electronics students, hobbyists, and practicing engineers looking for a clear, practical guide to JFET technology.
Happy May and Taurus Season.
♥☽✷♥We have a large viewing audience for Presentations. So far my Free Workshop Presentations are doing excellent on views. I just started weeks ago within May. I am also sponsoring Alison within my blog and courses upcoming. See our Temple office for ongoing weekly updates.
https://ldmchapels.weebly.com
♥☽About: I am Adult EDU Vocational, Ordained, Certified and Experienced. Course genres are personal development for holistic health, healing, and self care/self serve.
Title: A Quick and Illustrated Guide to APA Style Referencing (7th Edition)
This visual and beginner-friendly guide simplifies the APA referencing style (7th edition) for academic writing. Designed especially for commerce students and research beginners, it includes:
✅ Real examples from original research papers
✅ Color-coded diagrams for clarity
✅ Key rules for in-text citation and reference list formatting
✅ Free citation tools like Mendeley & Zotero explained
Whether you're writing a college assignment, dissertation, or academic article, this guide will help you cite your sources correctly, confidently, and consistent.
Created by: Prof. Ishika Ghosh,
Faculty.
📩 For queries or feedback: [email protected]
10. Python Casting
x = int(1) # x will be 1
x = float(1) # x will be 1.0
w = float("4.2") # w will be 4.2
x = str("s1") # x will be 's1'
11. Python Strings
❮ Previous
Next ❯
Strings in python are surrounded by either single
quotation marks, or double quotation marks.
'hello' is the same as "hello".
You can display a string literal with the print()
function:
print("Hello")
print('Hello')
12. Python - Slicing Strings
❮ Previous
Next ❯
b = "Hello, World!"
print(b[2:5])
Starting from start
b = "Hello, World!"
print(b[:5])
13. Python - Modify Strings
❮ Previous
Next ❯
The upper() method returns the string in upper case:
a = "Hello, World!"
print(a.upper())
The lower() method returns the string in lower case:
a = "Hello, World!"
print(a.lower())
14. Python - String Concatenation
❮ Previous
Next ❯
a = "Hello"
b = "World"
c = a + b
print(c)
15. age = 36
txt = "My name is John, I am " + age
print(txt)
F string in python
age = 36
txt = f"My name is John, I am {age}"
print(txt)
18. Python Lists
Lists are used to store multiple items in a single variable.
Lists are one of 4 built-in data types in Python used to store
collections of data, the other 3 are Tuple, Set, and Dictionary, all
with different qualities and usage.
Lists are created using square brackets:
Create a List:
thislist = ["apple", "banana", "cherry"]
print(thislist)
19. List Contd….
Allow Duplicates
Since lists are indexed, lists can have items with the same
value:
Lists allow duplicate values:
thislist = ["apple", "banana", "cherry",
"apple", "cherry"]
print(thislist)
23. Python - Loop Lists
thislist = ["apple", "banana", "cherry"]
for x in thislist:
print(x)
By using For Loop
thislist = ["apple", "banana", "cherry"]
for i in range(len(thislist)):
print(thislist[i])
25. Python - Copy Lists
You cannot copy a list simply by typing list2 = list1,
because: list2 will only be a reference to list1, and
changes made in list1 will automatically also be made in
list2.
There are ways to make a copy, one way is to use the
built-in List method copy().
thislist = ["apple", "banana", "cherry"]
mylist = thislist.copy()
print(mylist)
26. Python - Join Lists
list1 = ["a", "b", "c"]
list2 = [1, 2, 3]
list3 = list1 + list2
print(list3)
Another method
for x in list2:
list1.append(x)
28. Python Tuples
● A tuple is an immutable, ordered collection of items in
Python.
● Tuples are defined by enclosing the elements in
parentheses ().
tupple = ("apple", "banana", "cherry")
print(tupple)
29. Python Sets
Definition:
● A set is an unordered collection of unique elements in Python.
● Sets are defined by enclosing elements in curly braces {} or
using the set() function.
Key Characteristics:
● Unordered: No indexing or slicing.
● Unique: No duplicate elements allowed.
30. Contd…
# Creating a set with curly braces
my_set = {1, 2, 3, 4}
# Creating a set using the set() function
another_set = set([5, 6, 7, 8])
# Creating an empty set (must use set() function, not {})
empty_set = set()
31. Adding and Removing Elements
# Adding a single element
my_set.add(5)
print(my_set) # Output: {1, 2, 3, 4, 5}
# Adding multiple elements
my_set.update([6, 7])
print(my_set) # Output: {1, 2, 3, 4, 5, 6, 7}
32. # Removing a specific element (raises KeyError if not found)
my_set.remove(7)
print(my_set) # Output: {1, 2, 3, 4, 5, 6}
# Discarding a specific element (does not raise an error if not
found)
my_set.discard(6)
print(my_set) # Output: {1, 2, 3, 4, 5}
33. # Union of two sets
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = set1 | set2
print(union_set) # Output: {1, 2, 3, 4, 5}
34. Python Dictionaries
Definition:
● A dictionary is an unordered collection of key-value pairs
in Python.
● Dictionaries are defined by enclosing key-value pairs in
curly braces {} with a colon : separating keys and
values.
Key Characteristics:
● Unordered: No indexing or slicing.
● Mutable: Can change the content.
35. Contd…
# Creating a dictionary with curly braces
my_dict = {'name': 'Alice', 'age': 25, 'city': 'New York'}
# Creating a dictionary using the dict() function
another_dict = dict(name='Bob', age=30, city='San
Francisco')
# Creating an empty dictionary
empty_dict = {}
36. # Accessing a value by its key
print(my_dict['name']) # Output: Alice
# Using the get() method
print(my_dict.get('age')) # Output: 25
# Accessing a value by its key
print(my_dict['name']) # Output: Alice
# Using the get() method
print(my_dict.get('age')) # Output: 25
37. # Using the pop() method
removed_value = my_dict.pop('city')
print(removed_value) # Output: New York
print(my_dict) # Output: {'name': 'Alice', 'age': 26, 'email':
'[email protected]'}
# Using the del statement
del my_dict['email']
print(my_dict) # Output: {'name': 'Alice', 'age': 26}
39. # Iterating over keys
for key in my_dict:
print(key, my_dict[key]) # Output: name Alice
# Iterating over key-value pairs
for key, value in my_dict.items():
print(key, value) # Output: name Alice
40. Python If ... Else
a = 200
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")
41. Python While Loops
i = 1
while i < 6:
print(i)
i += 1
Using Break
Break loop for some condition
42. Python For Loops
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
for x in "banana":
print(x)
43. Python Functions
Definition:
● A function is a block of organized, reusable code that
performs a specific task.
● Functions help break programs into smaller, manageable,
and modular chunks.
Key Characteristics:
● Improve code reusability and readability.
50. def print_info(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
print_info(name="Alice", age=25, city="New York")
# Output:
# name: Alice
# age: 25
# city: New York
51. Lambda Function
● A lambda function is a small anonymous function defined
using the lambda keyword.
x = lambda a : a + 10
print(x(5))