SlideShare a Scribd company logo
1 of 20
Python with AI – I
Session 3
More about lists
Definition: A generic term for a programming data structure that holds multiple
items. Essentially, it holds a group of elements.
Common Array Functions: insert (append), delete, length, sort (specific types of
sorting), and many more
Notes:
- All languages have some form of an array, many languages refer to this concept
as a list
- Memory and run-time efficient
Examples of Lists & Common Methods
# empty list
my_list = []
# list of integers
my_list = [1, 2, 3]
# list with mixed data types
my_list = [1, "Hello", 3.4]
# nested list (array inside of an array)
my_list = ["mouse", [8, 4, 6], ['a']]
* Question: How can we access "mouse" or ['a']? *
Adding & Removing Elements - Lists
Adding items to Lists:
myList = ['apple','mango']
myList.append('orange')
myList.append('grapes')
myList.append('strawberry')
myList.append('kiwi')
print(myList)
# Output:
['apple', 'mango', 'orange', 'grapes',
'strawberry', 'kiwi']
Remove Elements in a List:
myList1 = ['a','b','c']
myList1.remove('a')
myList1.remove('b')
myList1.remove('c')
# Output:
[]
Note* : Even though there are no elements
in the list, it still takes up memory, we
can still add elements!
Integrating Loops - Lists
Iterating Through Lists:
myList = ['apple','banana','mango']
for fruit in myList:
print("I like", fruit)
# Output:
I like apple
I like banana
I like mango
Combining Elements in 2 Lists:
myList1 = ['a','b','c']
myList2 = [1,2,3]
for value in myList2:
myList1.append(value)
# Output:
['a','b','c', 1, 2, 3]
Sorting & Length - Lists
Lists:
• A list holds ordered collection of items
• Items can be Strings, Integers, Floats, and custom Data Types
Sorting & Length:
• .sort() implementation orders the collection of items from decreasing to
increasing value, by default
• reverse property - (increasing to decreasing)
• key property - (user’s custom sort)
• len() - gives the total amount of elements in the collection (list)
Sorting & Length Examples - List
myList = []
myList.append('apple')
myList.append('grapes')
myList.append('carrots')
myList.sort()
print(myList)
# Output:
['apple', 'carrots', 'grapes']
myList.sort(reverse = True)
print(myList)
# Output:
['grapes', 'carrots', 'apple']
print('I have ', len(myList),' items
to purchase')
# Output:
I have 3 items to purchase
List Concept Practice Questions
Note: Please use your Repl accounts to test code and to save files for all classes
• 2 Questions
Question 1:
list1 = ["Hello ", "Hi"]
list2 = ["Goodbye", "Bye"]
Desired Output:
# Output:
List3 = ['Hello', 'Hi', 'Goodbye',
'Bye']
Question 2:
morningFoods = ["toast", "tea",
"apples"]
Desired Output:
# Output:
There was toast in breakfast
There was tea in breakfast
There was apples in breakfast
Dictionaries - Data Structure
Definition: A dictionary consists of a collection of key-value pairs. Each key-value
pair maps the key to its respective value.
Notes:
- Similar to a list in terms of methods that can be used
- Key (a), Value (b) paired
- Keys are represented using Strings only, Values can be any value
Dictionaries - Code Implementation
Dictionary Representation:
d = dict([(<key>, <value>),
(<key>, <value),
(<key>, <value>)])
MLB_team = dict([('Colorado', 'Rockies'),
('Boston', 'Red Sox'),
('Minnesota', 'Twins'),
('Milwaukee', 'Brewers'),
('Seattle', 'Mariners')])
Note* : Dictionaries can also be represented using:
d = {<key> : <value>, <key> : <value>}
MLB_team = {'Colorado' : 'Rockies', 'Boston', : 'Red Sox', …}
* Note: Dictionaries are different than lists!
Can’t be indexed using indices. Must be
accessed by keys.
MLB_team[1]
Traceback (most recent call last):
File "<pyshell#13>", line 1, in <module>
MLB_team[1]
KeyError:
Dictionaries - Retrieving Values
Printing Dictionary Values:
print('The Boston team name is', MLB_Team['Boston'])
# Output: 'The Boston team name is','Red Sox'
Deleting Dictionary Values:
del MLB_Team['Boston']
Printing Dictionary Values:
print(MLB_Team)
# Output: {'Boston': 'Red Sox', 'Milwaukee': 'Brewers', 'Colorado': 'Rockies', 'Seattle':
'Mariners', 'Minnesota': 'Twins'}
Dictionaries - Using Loops (Keys & Values)
Printing Keys & Values:
for key in MLB_team:
print(key)
print(MLB_team[key])
# Output: Boston Milwaukee Colorado
Seattle Minnesota
# Output: Red Sox Brewers Rockies
Mariners Twins
Checking For Specific Value:
for key in MLB_team:
if MLB_team[key] == 'Red Sox':
print('Found Boston')
break
else:
print(Missed Boston')
# Output: Found Boston
Note* : An alternative for quicker key, value search is:
if "Boston" in MLB_team:
print("Found Boston")
Dictionary Concept Practice Questions
Given Input:
d = {0: 10, 1: 20}
Desired Output:
- Update the dictionary,
such that it has the
given new integer set
# Output:
d = {0: 10, 1: 20, 2: 30}
Given Input:
d = {1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60}
Desired Output:
- Write a method, isKeyPresent, that determines whether or
not a given key is present in the dictionary. Assume the
key can be any type (String, Int, Float, etc..).
isKeyPresent(5) // true or false
isKeyPresent(9) // true or false
# Output:
True
False
Modules in Python
● Use multiple functions written by others
● Popular packages: numpy, pandas
● How to install these packages with Python?
import pandas
import numpy
Modules in Python - Numpy
• Useful for various array and matrix representation of elements
• Many functions are analogous to List data structure
import numpy as np
list_sample = [5,6,7,8]
numpy = np.array(list_sample)
print(numpy[0])
# Output: 5
Modules in Python - Pandas
• DataFrame: Two dimensional frame that has rows and columns and
multiple streams of input
import pandas as pd
df = pd.DataFrame({'X':[78,85,96,80,86], 'Y':[84,94,89,83,86],'Z':[86,97,96,72,83]});
print(df)
# Output:
X Y Z
0 78 84 86
1 85 94 97
2 96 89 96
3 80 83 72
4 86 86 83
Modules in Python - Pandas
• DataSeries: Two dimensional frame that has rows and columns, but
contains only one collection as input
import pandas as pd
ds = pd.Series([2, 4, 6, 8, 10])
print(s)
# Output:
0 2
1 4
2 6
3 8
4 10
Note* : Look at previous slide to
compare/contrast initializations of
DataFrame vs DataSeries
Modules in Python - Pandas
• Pandas is useful and important for reading CSV files, the datasets used for
training models
import pandas as pd
dataset = pd.read_csv(.csv’)
print(dataset.head())
print(dataset.dtypes)
• .head(n) - retrieves the top n (Integer) rows from the given dataset
• .dtypes() - retrieves the column title and its respective data type
Measuring Run Time of Code
import time
start_time = time.time()
//
main()
//
seconds = time.time() - start_time
print('Time Taken:', time.strftime("%H:%M:%S", time.gmtime(seconds)))
# Output: Time Taken: 00:00:08
● Main() is the function that contains the code to be executed
● We use the time library to ease with measuring run time, various
time zones, and more
http://aiclub.world

More Related Content

What's hot

PHP Unit 4 arrays
PHP Unit 4 arraysPHP Unit 4 arrays
PHP Unit 4 arraysKumar
 
Python programming -Tuple and Set Data type
Python programming -Tuple and Set Data typePython programming -Tuple and Set Data type
Python programming -Tuple and Set Data typeMegha V
 
Python fundamentals - basic | WeiYuan
Python fundamentals - basic | WeiYuanPython fundamentals - basic | WeiYuan
Python fundamentals - basic | WeiYuanWei-Yuan Chang
 
Introduction to the basics of Python programming (part 3)
Introduction to the basics of Python programming (part 3)Introduction to the basics of Python programming (part 3)
Introduction to the basics of Python programming (part 3)Pedro Rodrigues
 
Scala in a Java 8 World
Scala in a Java 8 WorldScala in a Java 8 World
Scala in a Java 8 WorldDaniel Blyth
 
Python于Web 2.0网站的应用 - QCon Beijing 2010
Python于Web 2.0网站的应用 - QCon Beijing 2010Python于Web 2.0网站的应用 - QCon Beijing 2010
Python于Web 2.0网站的应用 - QCon Beijing 2010Qiangning Hong
 
Brixton Library Technology Initiative
Brixton Library Technology InitiativeBrixton Library Technology Initiative
Brixton Library Technology InitiativeBasil Bibi
 
Introduction to R
Introduction to RIntroduction to R
Introduction to Rvpletap
 
Introduction to Python and TensorFlow
Introduction to Python and TensorFlowIntroduction to Python and TensorFlow
Introduction to Python and TensorFlowBayu Aldi Yansyah
 
How to Become a Tree Hugger: Random Forests and Predictive Modeling for Devel...
How to Become a Tree Hugger: Random Forests and Predictive Modeling for Devel...How to Become a Tree Hugger: Random Forests and Predictive Modeling for Devel...
How to Become a Tree Hugger: Random Forests and Predictive Modeling for Devel...Matt Harrison
 
Analysis of Fatal Utah Avalanches with Python. From Scraping, Analysis, to In...
Analysis of Fatal Utah Avalanches with Python. From Scraping, Analysis, to In...Analysis of Fatal Utah Avalanches with Python. From Scraping, Analysis, to In...
Analysis of Fatal Utah Avalanches with Python. From Scraping, Analysis, to In...Matt Harrison
 
Learn 90% of Python in 90 Minutes
Learn 90% of Python in 90 MinutesLearn 90% of Python in 90 Minutes
Learn 90% of Python in 90 MinutesMatt Harrison
 
GDI Seattle - Intro to JavaScript Class 2
GDI Seattle - Intro to JavaScript Class 2GDI Seattle - Intro to JavaScript Class 2
GDI Seattle - Intro to JavaScript Class 2Heather Rock
 

What's hot (20)

Python programming : List and tuples
Python programming : List and tuplesPython programming : List and tuples
Python programming : List and tuples
 
PHP Unit 4 arrays
PHP Unit 4 arraysPHP Unit 4 arrays
PHP Unit 4 arrays
 
Pa1 lists subset
Pa1 lists subsetPa1 lists subset
Pa1 lists subset
 
Python programming -Tuple and Set Data type
Python programming -Tuple and Set Data typePython programming -Tuple and Set Data type
Python programming -Tuple and Set Data type
 
Python fundamentals - basic | WeiYuan
Python fundamentals - basic | WeiYuanPython fundamentals - basic | WeiYuan
Python fundamentals - basic | WeiYuan
 
Chap 3php array part1
Chap 3php array part1Chap 3php array part1
Chap 3php array part1
 
Introduction to the basics of Python programming (part 3)
Introduction to the basics of Python programming (part 3)Introduction to the basics of Python programming (part 3)
Introduction to the basics of Python programming (part 3)
 
Scala in a Java 8 World
Scala in a Java 8 WorldScala in a Java 8 World
Scala in a Java 8 World
 
Python于Web 2.0网站的应用 - QCon Beijing 2010
Python于Web 2.0网站的应用 - QCon Beijing 2010Python于Web 2.0网站的应用 - QCon Beijing 2010
Python于Web 2.0网站的应用 - QCon Beijing 2010
 
Arrays in PHP
Arrays in PHPArrays in PHP
Arrays in PHP
 
Brixton Library Technology Initiative
Brixton Library Technology InitiativeBrixton Library Technology Initiative
Brixton Library Technology Initiative
 
R workshop
R workshopR workshop
R workshop
 
4.1 PHP Arrays
4.1 PHP Arrays4.1 PHP Arrays
4.1 PHP Arrays
 
Dictionaries in python
Dictionaries in pythonDictionaries in python
Dictionaries in python
 
Introduction to R
Introduction to RIntroduction to R
Introduction to R
 
Introduction to Python and TensorFlow
Introduction to Python and TensorFlowIntroduction to Python and TensorFlow
Introduction to Python and TensorFlow
 
How to Become a Tree Hugger: Random Forests and Predictive Modeling for Devel...
How to Become a Tree Hugger: Random Forests and Predictive Modeling for Devel...How to Become a Tree Hugger: Random Forests and Predictive Modeling for Devel...
How to Become a Tree Hugger: Random Forests and Predictive Modeling for Devel...
 
Analysis of Fatal Utah Avalanches with Python. From Scraping, Analysis, to In...
Analysis of Fatal Utah Avalanches with Python. From Scraping, Analysis, to In...Analysis of Fatal Utah Avalanches with Python. From Scraping, Analysis, to In...
Analysis of Fatal Utah Avalanches with Python. From Scraping, Analysis, to In...
 
Learn 90% of Python in 90 Minutes
Learn 90% of Python in 90 MinutesLearn 90% of Python in 90 Minutes
Learn 90% of Python in 90 Minutes
 
GDI Seattle - Intro to JavaScript Class 2
GDI Seattle - Intro to JavaScript Class 2GDI Seattle - Intro to JavaScript Class 2
GDI Seattle - Intro to JavaScript Class 2
 

Similar to Pa1 session 3_slides

Python Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, DictionaryPython Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, DictionarySoba Arjun
 
File handling in pythan.pptx
File handling in pythan.pptxFile handling in pythan.pptx
File handling in pythan.pptxNawalKishore38
 
Pythonlearn-08-Lists.pptx
Pythonlearn-08-Lists.pptxPythonlearn-08-Lists.pptx
Pythonlearn-08-Lists.pptxMihirDatir
 
python-numpyandpandas-170922144956 (1).pptx
python-numpyandpandas-170922144956 (1).pptxpython-numpyandpandas-170922144956 (1).pptx
python-numpyandpandas-170922144956 (1).pptxAkashgupta517936
 
Matplotlib adalah pustaka plotting 2D Python yang menghasilkan gambar berkual...
Matplotlib adalah pustaka plotting 2D Python yang menghasilkan gambar berkual...Matplotlib adalah pustaka plotting 2D Python yang menghasilkan gambar berkual...
Matplotlib adalah pustaka plotting 2D Python yang menghasilkan gambar berkual...HendraPurnama31
 
python cheat sheat, Data science, Machine learning
python cheat sheat, Data science, Machine learningpython cheat sheat, Data science, Machine learning
python cheat sheat, Data science, Machine learningTURAGAVIJAYAAKASH
 
Beginner's Python Cheat Sheet
Beginner's Python Cheat SheetBeginner's Python Cheat Sheet
Beginner's Python Cheat SheetVerxus
 
beginners_python_cheat_sheet_pcc_all (1).pdf
beginners_python_cheat_sheet_pcc_all (1).pdfbeginners_python_cheat_sheet_pcc_all (1).pdf
beginners_python_cheat_sheet_pcc_all (1).pdfElNew2
 
Python - Numpy/Pandas/Matplot Machine Learning Libraries
Python - Numpy/Pandas/Matplot Machine Learning LibrariesPython - Numpy/Pandas/Matplot Machine Learning Libraries
Python - Numpy/Pandas/Matplot Machine Learning LibrariesAndrew Ferlitsch
 
Unit 3_Numpy_Vsp.pptx
Unit 3_Numpy_Vsp.pptxUnit 3_Numpy_Vsp.pptx
Unit 3_Numpy_Vsp.pptxprakashvs7
 
Beginners python cheat sheet - Basic knowledge
Beginners python cheat sheet - Basic knowledge Beginners python cheat sheet - Basic knowledge
Beginners python cheat sheet - Basic knowledge O T
 
beginners_python_cheat_sheet_pcc_all (3).pptx
beginners_python_cheat_sheet_pcc_all (3).pptxbeginners_python_cheat_sheet_pcc_all (3).pptx
beginners_python_cheat_sheet_pcc_all (3).pptxHongAnhNguyn285885
 
INFORMATIVE ESSAYThe purpose of the Informative Essay assignme.docx
INFORMATIVE ESSAYThe purpose of the Informative Essay assignme.docxINFORMATIVE ESSAYThe purpose of the Informative Essay assignme.docx
INFORMATIVE ESSAYThe purpose of the Informative Essay assignme.docxcarliotwaycave
 
Datastructures in python
Datastructures in pythonDatastructures in python
Datastructures in pythonhydpy
 
Python elements list you can study .pdf
Python elements list you can study  .pdfPython elements list you can study  .pdf
Python elements list you can study .pdfAUNGHTET61
 
第二讲 Python基礎
第二讲 Python基礎第二讲 Python基礎
第二讲 Python基礎juzihua1102
 

Similar to Pa1 session 3_slides (20)

Python Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, DictionaryPython Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, Dictionary
 
File handling in pythan.pptx
File handling in pythan.pptxFile handling in pythan.pptx
File handling in pythan.pptx
 
Pythonlearn-08-Lists.pptx
Pythonlearn-08-Lists.pptxPythonlearn-08-Lists.pptx
Pythonlearn-08-Lists.pptx
 
python-numpyandpandas-170922144956 (1).pptx
python-numpyandpandas-170922144956 (1).pptxpython-numpyandpandas-170922144956 (1).pptx
python-numpyandpandas-170922144956 (1).pptx
 
Matplotlib adalah pustaka plotting 2D Python yang menghasilkan gambar berkual...
Matplotlib adalah pustaka plotting 2D Python yang menghasilkan gambar berkual...Matplotlib adalah pustaka plotting 2D Python yang menghasilkan gambar berkual...
Matplotlib adalah pustaka plotting 2D Python yang menghasilkan gambar berkual...
 
2. Python Cheat Sheet.pdf
2. Python Cheat Sheet.pdf2. Python Cheat Sheet.pdf
2. Python Cheat Sheet.pdf
 
python cheat sheat, Data science, Machine learning
python cheat sheat, Data science, Machine learningpython cheat sheat, Data science, Machine learning
python cheat sheat, Data science, Machine learning
 
Beginner's Python Cheat Sheet
Beginner's Python Cheat SheetBeginner's Python Cheat Sheet
Beginner's Python Cheat Sheet
 
beginners_python_cheat_sheet_pcc_all (1).pdf
beginners_python_cheat_sheet_pcc_all (1).pdfbeginners_python_cheat_sheet_pcc_all (1).pdf
beginners_python_cheat_sheet_pcc_all (1).pdf
 
Python - Numpy/Pandas/Matplot Machine Learning Libraries
Python - Numpy/Pandas/Matplot Machine Learning LibrariesPython - Numpy/Pandas/Matplot Machine Learning Libraries
Python - Numpy/Pandas/Matplot Machine Learning Libraries
 
Unit 3_Numpy_Vsp.pptx
Unit 3_Numpy_Vsp.pptxUnit 3_Numpy_Vsp.pptx
Unit 3_Numpy_Vsp.pptx
 
Aggregate.pptx
Aggregate.pptxAggregate.pptx
Aggregate.pptx
 
Beginners python cheat sheet - Basic knowledge
Beginners python cheat sheet - Basic knowledge Beginners python cheat sheet - Basic knowledge
Beginners python cheat sheet - Basic knowledge
 
1. python
1. python1. python
1. python
 
Python cheatsheet for beginners
Python cheatsheet for beginnersPython cheatsheet for beginners
Python cheatsheet for beginners
 
beginners_python_cheat_sheet_pcc_all (3).pptx
beginners_python_cheat_sheet_pcc_all (3).pptxbeginners_python_cheat_sheet_pcc_all (3).pptx
beginners_python_cheat_sheet_pcc_all (3).pptx
 
INFORMATIVE ESSAYThe purpose of the Informative Essay assignme.docx
INFORMATIVE ESSAYThe purpose of the Informative Essay assignme.docxINFORMATIVE ESSAYThe purpose of the Informative Essay assignme.docx
INFORMATIVE ESSAYThe purpose of the Informative Essay assignme.docx
 
Datastructures in python
Datastructures in pythonDatastructures in python
Datastructures in python
 
Python elements list you can study .pdf
Python elements list you can study  .pdfPython elements list you can study  .pdf
Python elements list you can study .pdf
 
第二讲 Python基礎
第二讲 Python基礎第二讲 Python基礎
第二讲 Python基礎
 

More from aiclub_slides

Linear regression middleschool
Linear regression middleschoolLinear regression middleschool
Linear regression middleschoolaiclub_slides
 
Pa2 project template
Pa2 project templatePa2 project template
Pa2 project templateaiclub_slides
 
Knn intro advanced_middleschool
Knn intro advanced_middleschoolKnn intro advanced_middleschool
Knn intro advanced_middleschoolaiclub_slides
 
M1 regression metrics_middleschool
M1 regression metrics_middleschoolM1 regression metrics_middleschool
M1 regression metrics_middleschoolaiclub_slides
 
Ai in real life face detection
Ai in real life   face detectionAi in real life   face detection
Ai in real life face detectionaiclub_slides
 
Res net high level intro
Res net high level introRes net high level intro
Res net high level introaiclub_slides
 
Neural networks and flattened images
Neural networks and flattened imagesNeural networks and flattened images
Neural networks and flattened imagesaiclub_slides
 
What is a_neural_network
What is a_neural_networkWhat is a_neural_network
What is a_neural_networkaiclub_slides
 
How neural networks learn part iii
How neural networks learn part iiiHow neural networks learn part iii
How neural networks learn part iiiaiclub_slides
 
Introduction to deep learning image classification
Introduction to deep learning   image classificationIntroduction to deep learning   image classification
Introduction to deep learning image classificationaiclub_slides
 
Accuracy middleschool
Accuracy middleschoolAccuracy middleschool
Accuracy middleschoolaiclub_slides
 
Introduction to classification_middleschool
Introduction to classification_middleschoolIntroduction to classification_middleschool
Introduction to classification_middleschoolaiclub_slides
 
Introduction to the cloud
Introduction to the cloudIntroduction to the cloud
Introduction to the cloudaiclub_slides
 
Ai lifecycle and navigator
Ai lifecycle and navigatorAi lifecycle and navigator
Ai lifecycle and navigatoraiclub_slides
 

More from aiclub_slides (20)

Linear regression middleschool
Linear regression middleschoolLinear regression middleschool
Linear regression middleschool
 
Pa2 project template
Pa2 project templatePa2 project template
Pa2 project template
 
Knn intro advanced_middleschool
Knn intro advanced_middleschoolKnn intro advanced_middleschool
Knn intro advanced_middleschool
 
M1 regression metrics_middleschool
M1 regression metrics_middleschoolM1 regression metrics_middleschool
M1 regression metrics_middleschool
 
Pa1 json requests
Pa1 json requestsPa1 json requests
Pa1 json requests
 
Mnist images
Mnist imagesMnist images
Mnist images
 
Mnist images
Mnist imagesMnist images
Mnist images
 
Ai in real life face detection
Ai in real life   face detectionAi in real life   face detection
Ai in real life face detection
 
Cnn
CnnCnn
Cnn
 
Res net high level intro
Res net high level introRes net high level intro
Res net high level intro
 
Neural networks and flattened images
Neural networks and flattened imagesNeural networks and flattened images
Neural networks and flattened images
 
What is a_neural_network
What is a_neural_networkWhat is a_neural_network
What is a_neural_network
 
How neural networks learn part iii
How neural networks learn part iiiHow neural networks learn part iii
How neural networks learn part iii
 
Introduction to deep learning image classification
Introduction to deep learning   image classificationIntroduction to deep learning   image classification
Introduction to deep learning image classification
 
Accuracy middleschool
Accuracy middleschoolAccuracy middleschool
Accuracy middleschool
 
Introduction to classification_middleschool
Introduction to classification_middleschoolIntroduction to classification_middleschool
Introduction to classification_middleschool
 
Introduction to the cloud
Introduction to the cloudIntroduction to the cloud
Introduction to the cloud
 
Basics of data
Basics of dataBasics of data
Basics of data
 
Ai basics
Ai basicsAi basics
Ai basics
 
Ai lifecycle and navigator
Ai lifecycle and navigatorAi lifecycle and navigator
Ai lifecycle and navigator
 

Recently uploaded

Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersSabitha Banu
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaVirag Sontakke
 
Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...jaredbarbolino94
 
Capitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitolTechU
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementmkooblal
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Celine George
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxJiesonDelaCerna
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxAvyJaneVismanos
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentInMediaRes1
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfMahmoud M. Sallam
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 

Recently uploaded (20)

Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginners
 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of India
 
Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
Capitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptx
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of management
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptx
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptx
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media Component
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdf
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 

Pa1 session 3_slides

  • 1. Python with AI – I Session 3
  • 2. More about lists Definition: A generic term for a programming data structure that holds multiple items. Essentially, it holds a group of elements. Common Array Functions: insert (append), delete, length, sort (specific types of sorting), and many more Notes: - All languages have some form of an array, many languages refer to this concept as a list - Memory and run-time efficient
  • 3. Examples of Lists & Common Methods # empty list my_list = [] # list of integers my_list = [1, 2, 3] # list with mixed data types my_list = [1, "Hello", 3.4] # nested list (array inside of an array) my_list = ["mouse", [8, 4, 6], ['a']] * Question: How can we access "mouse" or ['a']? *
  • 4. Adding & Removing Elements - Lists Adding items to Lists: myList = ['apple','mango'] myList.append('orange') myList.append('grapes') myList.append('strawberry') myList.append('kiwi') print(myList) # Output: ['apple', 'mango', 'orange', 'grapes', 'strawberry', 'kiwi'] Remove Elements in a List: myList1 = ['a','b','c'] myList1.remove('a') myList1.remove('b') myList1.remove('c') # Output: [] Note* : Even though there are no elements in the list, it still takes up memory, we can still add elements!
  • 5. Integrating Loops - Lists Iterating Through Lists: myList = ['apple','banana','mango'] for fruit in myList: print("I like", fruit) # Output: I like apple I like banana I like mango Combining Elements in 2 Lists: myList1 = ['a','b','c'] myList2 = [1,2,3] for value in myList2: myList1.append(value) # Output: ['a','b','c', 1, 2, 3]
  • 6. Sorting & Length - Lists Lists: • A list holds ordered collection of items • Items can be Strings, Integers, Floats, and custom Data Types Sorting & Length: • .sort() implementation orders the collection of items from decreasing to increasing value, by default • reverse property - (increasing to decreasing) • key property - (user’s custom sort) • len() - gives the total amount of elements in the collection (list)
  • 7. Sorting & Length Examples - List myList = [] myList.append('apple') myList.append('grapes') myList.append('carrots') myList.sort() print(myList) # Output: ['apple', 'carrots', 'grapes'] myList.sort(reverse = True) print(myList) # Output: ['grapes', 'carrots', 'apple'] print('I have ', len(myList),' items to purchase') # Output: I have 3 items to purchase
  • 8. List Concept Practice Questions Note: Please use your Repl accounts to test code and to save files for all classes • 2 Questions Question 1: list1 = ["Hello ", "Hi"] list2 = ["Goodbye", "Bye"] Desired Output: # Output: List3 = ['Hello', 'Hi', 'Goodbye', 'Bye'] Question 2: morningFoods = ["toast", "tea", "apples"] Desired Output: # Output: There was toast in breakfast There was tea in breakfast There was apples in breakfast
  • 9. Dictionaries - Data Structure Definition: A dictionary consists of a collection of key-value pairs. Each key-value pair maps the key to its respective value. Notes: - Similar to a list in terms of methods that can be used - Key (a), Value (b) paired - Keys are represented using Strings only, Values can be any value
  • 10. Dictionaries - Code Implementation Dictionary Representation: d = dict([(<key>, <value>), (<key>, <value), (<key>, <value>)]) MLB_team = dict([('Colorado', 'Rockies'), ('Boston', 'Red Sox'), ('Minnesota', 'Twins'), ('Milwaukee', 'Brewers'), ('Seattle', 'Mariners')]) Note* : Dictionaries can also be represented using: d = {<key> : <value>, <key> : <value>} MLB_team = {'Colorado' : 'Rockies', 'Boston', : 'Red Sox', …} * Note: Dictionaries are different than lists! Can’t be indexed using indices. Must be accessed by keys. MLB_team[1] Traceback (most recent call last): File "<pyshell#13>", line 1, in <module> MLB_team[1] KeyError:
  • 11. Dictionaries - Retrieving Values Printing Dictionary Values: print('The Boston team name is', MLB_Team['Boston']) # Output: 'The Boston team name is','Red Sox' Deleting Dictionary Values: del MLB_Team['Boston'] Printing Dictionary Values: print(MLB_Team) # Output: {'Boston': 'Red Sox', 'Milwaukee': 'Brewers', 'Colorado': 'Rockies', 'Seattle': 'Mariners', 'Minnesota': 'Twins'}
  • 12. Dictionaries - Using Loops (Keys & Values) Printing Keys & Values: for key in MLB_team: print(key) print(MLB_team[key]) # Output: Boston Milwaukee Colorado Seattle Minnesota # Output: Red Sox Brewers Rockies Mariners Twins Checking For Specific Value: for key in MLB_team: if MLB_team[key] == 'Red Sox': print('Found Boston') break else: print(Missed Boston') # Output: Found Boston Note* : An alternative for quicker key, value search is: if "Boston" in MLB_team: print("Found Boston")
  • 13. Dictionary Concept Practice Questions Given Input: d = {0: 10, 1: 20} Desired Output: - Update the dictionary, such that it has the given new integer set # Output: d = {0: 10, 1: 20, 2: 30} Given Input: d = {1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60} Desired Output: - Write a method, isKeyPresent, that determines whether or not a given key is present in the dictionary. Assume the key can be any type (String, Int, Float, etc..). isKeyPresent(5) // true or false isKeyPresent(9) // true or false # Output: True False
  • 14. Modules in Python ● Use multiple functions written by others ● Popular packages: numpy, pandas ● How to install these packages with Python? import pandas import numpy
  • 15. Modules in Python - Numpy • Useful for various array and matrix representation of elements • Many functions are analogous to List data structure import numpy as np list_sample = [5,6,7,8] numpy = np.array(list_sample) print(numpy[0]) # Output: 5
  • 16. Modules in Python - Pandas • DataFrame: Two dimensional frame that has rows and columns and multiple streams of input import pandas as pd df = pd.DataFrame({'X':[78,85,96,80,86], 'Y':[84,94,89,83,86],'Z':[86,97,96,72,83]}); print(df) # Output: X Y Z 0 78 84 86 1 85 94 97 2 96 89 96 3 80 83 72 4 86 86 83
  • 17. Modules in Python - Pandas • DataSeries: Two dimensional frame that has rows and columns, but contains only one collection as input import pandas as pd ds = pd.Series([2, 4, 6, 8, 10]) print(s) # Output: 0 2 1 4 2 6 3 8 4 10 Note* : Look at previous slide to compare/contrast initializations of DataFrame vs DataSeries
  • 18. Modules in Python - Pandas • Pandas is useful and important for reading CSV files, the datasets used for training models import pandas as pd dataset = pd.read_csv(.csv’) print(dataset.head()) print(dataset.dtypes) • .head(n) - retrieves the top n (Integer) rows from the given dataset • .dtypes() - retrieves the column title and its respective data type
  • 19. Measuring Run Time of Code import time start_time = time.time() // main() // seconds = time.time() - start_time print('Time Taken:', time.strftime("%H:%M:%S", time.gmtime(seconds))) # Output: Time Taken: 00:00:08 ● Main() is the function that contains the code to be executed ● We use the time library to ease with measuring run time, various time zones, and more