SlideShare a Scribd company logo
Welcome to the Brixton Library
Technology Initiative
(Coding for Adults)
ZCDixon@lambeth.gov.uk
BasilBibi@hotmail.com
January 30th 2016
Week 4 – Collections 1
Collections
• In computer science a collection is a grouping
of a variable number of data items (possibly
zero) that have some shared significance to
the problem being solved and need to be
operated upon together in some controlled
fashion – Wikipedia
• They formally belong to a group of data types
called Abstract Data Types.
Collections - Data Structures
• A data structure is a specialized format for organizing
and storing data. General data structure types include
the array, the file, the record, the table, the tree, and
so on.
Any data structure is designed to organize data to suit
a specific purpose so that it can be accessed and
worked with in appropriate ways. Wikipedia
• I will, in fact, claim that the difference between a bad
programmer and a good one is whether they consider
their code or their data structures more important. –
Linus Torvals (my minor change ‘he’ -> ‘they’ – sorry Linus )
Kinds of collections
• Different kinds of collections are Arrays, Lists,
Sets, Trees, Graphs and Maps or Dictionaries.
• Fixed-size arrays are usually not considered a
collection because they hold a fixed number
of data items, although they commonly play a
role in the implementation of collections.
• Variable-size arrays are generally considered
collections.
Python Collection Types
• In build types : list, set, dict, tuple
• collections module adds more :
• deque
• Counter
• OrderedDict : dict subclass that remembers the order
entries were added
• defaultdict : dict with missing values
Arrays, Python arrays and Lists
• In most computer languages an array is the simplest form
of collection.
• It is a sequence of memory positions that can be used to
store elements.
• Python considers the Array a special kind of List.
• The Python List has many very cool features that other
languages do not. These might be the reason to write
part or the whole of a system in Python.
Lists – indexed access
A sequence of memory positions that can be used to store elements.
# declare a variable myList of type List populated with elements 10 to 50
myList = [10, 20, 30, 40, 50]
# Can access the elements using an index.
print myList[3]
40
# Index position starts at zero.
print myList[0]
10
myList 10 20 30 40 50
index 0 1 2 3 4
Lists – indexed access
# Can use a variable to index elements in the array or list
index = 4
print myList [ index ]
50
# A access from the end using negative index
print myList [-1]
50
print myList[-3]
30
myList 10 20 30 40 50
index 0 1 2 3 4
-5 -4 -3 -2 -1
Lists – index out of range
# We get an IndexError when we try to index out of bounds
myList = [10, 20, 30, 40, 50]
print myList[ 20 ]
IndexError: list index out of range
Lists - slices
# Lists can be accessed using a ‘slice’
myList = [10, 20, 30, 40, 50]
# myList[ start : until ] UNTIL is not included
print myList [ 1 : 4 ]
[20,30,40]
# You can omit implied start and until
print myList [ : 4 ]
[10,20,30,40]
print myList [ 2 : ]
[30, 40, 50]
Lists - slices
# A slice can be defined in steps
myList = [10, 20, 30, 40, 50]
# myList[ start : until : step ]
print myList [ 1 : 4 : 2 ]
[20,40]
# With implied values for start and end
print myList [ : : 2]
[10, 30, 50]
print myList [ : : 3]
[10, 40]
Lists – assignment to slices
myList = [10,20,30,40,50]
# replace some values
myList[2:4] = ['C', 'D', 'E']
print myList
[10, 20, 'C', 'D', 'E', 50]
# now remove them by assigning an empty list to the same positions
myList[2:5] = []
print myList
[10, 20, 50]
# clear the list by replacing all the elements with an empty list
myList[:] = []
print myList
[]
Lists – Strings
# Strings are treated as a list
name = "Felix The House Cat“
print name[2:5]
'lix'
# Strings are immutable – you cannot change them :
name[2:5] = "CAN NOT DO THIS"
TypeError: 'str' object does not support item assignment
Lists – basic operation summary
Expression Result
myList[ 3 ] 40
myList[ 0 ] 10
index=4
myList[ index ]
50
myList[ -1 ] 50
myList[ -3 ] 30
myList[ 20 ] IndexError: list index out of range
myList[ 1 : 4 ] [20, 30, 40]
myList[ : 4] [10, 20, 30, 40]
myList[1:4:2] [20, 40]
myList[::2] [10, 30, 50]
myList[2:4] = ['C', 'D', 'E‘] [10, 20, 'C', 'D', 'E', 50]
myList[2:5] = [] [10, 20, 50]
myList[:] = [] []
myList[ : : -1 ] [50,40,30,20,10]
Given myList = [10,20,30,40,50]
Lists – more operations
Expression Result
remove(30) [10,20,40,50]
index(40) 3
index(99) ValueError: 99 is not in list
count(30) 1
append
reverse() [50, 40, 30, 20, 10]
Given myList = [10,20,30,40,50]
Lists – more expressions
Python Expression Results
len([1, 2, 3]) 3
[1, 2, 3] + [4, 5, 6] [1, 2, 3, 4, 5, 6]
['Hi!'] * 4 ['Hi!', 'Hi!', 'Hi!', 'Hi!']
3 in [1, 2, 3] True
Lists
Lists and arrays can be multidimensional.
Lists of lists.
myMulti = [ [1,2,3], ['a','b','c'], [100,200,300] ]
myMulti[ 0 ][ 2 ]
3
myMulti[ 1 ][ 1 ]
'b'
myMulti[ 1 ][ 1: ]
['b', 'c']
Arrays
• Array is different to List because all elements in an array must be the same
type
• myList = [10, 20, 'C', 'D', 'E', 30, 40, 50]
Python docs:
https://docs.python.org/2/library/array.html
The module defines the following type:
class array.array(typecode[, initializer])
A new array whose items are restricted by typecode, and initialized from
the optional initializer value, which must be a list, string, or iterable over
elements of the appropriate type.
Arrays - typecode
class array.array(typecode[, initializer])
Type code C Type Python Type
Minimum size in
bytes
'c' char character 1
'b' signed char int 1
'B' unsigned char int 1
'u' Py_UNICODE Unicode character 2 (see note)
'h' signed short int 2
'H' unsigned short int 2
'i' signed int int 2
'I' unsigned int long 2
'l' signed long int 4
'L' unsigned long long 4
'f' float float 4
'd' double float 8
myFloats = array.array( 'f' , [ 3.1415, 0.6931, 2.7182 ] )
Arrays – same type
import array
myIntArray = array.array('L', [10, 20, 30, 40, 50])
print myIntArray[1]
array.array('L', [10, 20, 'C', 'D', 'E', 30, 40, 50])
TypeError: an integer is required
Why Is Data Structure Choice Important?
Remember what Linus said about the importance of
data structures?
... whether they consider their code or their data
structures more important ...
Let’s see what he means.
Consider the differences between a List and an Array.
Why Chose List Or Array
• In most languages including Python List is
implemented as a chain of element positions
called a linked list.
• Adding to the front of a list is cheap.
• Adding to the end of a list is expensive
because we have to run along the whole list to
find the end and then add the new element.
10 20 30 40
Why Chose List Or Array
• Inserting an element in a list relatively cheap.
• Lists have the memory overhead of all the
pointers.
10 20 30 40
A
Why Chose List Or Array
With arrays we always know the length so adding an element to the end is very cheap.
Depending on how arrays are implemented in
your language :
Inserting is very expensive
because we have to take copies of
the parts and then glue back together.
Adding to the front of an array is very expensive
for the same reason.
Choosing the right data structure is important .
Special list and arrays - Stack, Queue, Deque
• A stack is a last in, first out (LIFO) data
structure
– Items are removed from a stack in the reverse
order from the way they were inserted
• A queue is a first in, first out (FIFO) data
structure
– Items are removed from a queue in the same
order as they were inserted
• A deque is a double-ended queue—items can
be inserted and removed at either end
Stack
Last In First out
Queue
First In First out
Deque – “deck” – Double ended Queue

More Related Content

What's hot

An Introduction to Tuple List Dictionary in Python
An Introduction to Tuple List Dictionary in PythonAn Introduction to Tuple List Dictionary in Python
An Introduction to Tuple List Dictionary in Python
yashar Aliabasi
 
Dictionary in python
Dictionary in pythonDictionary in python
Dictionary in python
vikram mahendra
 
Standard data-types-in-py
Standard data-types-in-pyStandard data-types-in-py
Standard data-types-in-py
Priyanshu Sengar
 
Python Workshop Part 2. LUG Maniapl
Python Workshop Part 2. LUG ManiaplPython Workshop Part 2. LUG Maniapl
Python Workshop Part 2. LUG Maniapl
Ankur Shrivastava
 
Python programming : List and tuples
Python programming : List and tuplesPython programming : List and tuples
Python programming : List and tuples
Emertxe Information Technologies Pvt Ltd
 
Sequence Types in Python Programming
Sequence Types in Python ProgrammingSequence Types in Python Programming
Sequence Types in Python Programming
Bobby Murugesan
 
Python Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, DictionaryPython Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, Dictionary
Soba Arjun
 
Python Collections
Python CollectionsPython Collections
Python Collections
sachingarg0
 
Python Datatypes by SujithKumar
Python Datatypes by SujithKumarPython Datatypes by SujithKumar
Python Datatypes by SujithKumar
Sujith Kumar
 
Values and Data types in python
Values and Data types in pythonValues and Data types in python
Values and Data types in python
Jothi Thilaga P
 
arrays of structures
arrays of structuresarrays of structures
arrays of structures
arushi bhatnagar
 
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
 
Chapter 15 Lists
Chapter 15 ListsChapter 15 Lists
Chapter 15 Lists
Praveen M Jigajinni
 
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
Megha V
 
Chapter 20 generic collections
Chapter 20   generic collectionsChapter 20   generic collections
Chapter 20 generic collections
CSDeptSriKaliswariCo
 
Lists
ListsLists
Java
JavaJava
Python Lecture 11
Python Lecture 11Python Lecture 11
Python Lecture 11
Inzamam Baig
 

What's hot (20)

An Introduction to Tuple List Dictionary in Python
An Introduction to Tuple List Dictionary in PythonAn Introduction to Tuple List Dictionary in Python
An Introduction to Tuple List Dictionary in Python
 
Dictionary in python
Dictionary in pythonDictionary in python
Dictionary in python
 
Standard data-types-in-py
Standard data-types-in-pyStandard data-types-in-py
Standard data-types-in-py
 
Array
ArrayArray
Array
 
Python Workshop Part 2. LUG Maniapl
Python Workshop Part 2. LUG ManiaplPython Workshop Part 2. LUG Maniapl
Python Workshop Part 2. LUG Maniapl
 
Python programming : List and tuples
Python programming : List and tuplesPython programming : List and tuples
Python programming : List and tuples
 
Sequence Types in Python Programming
Sequence Types in Python ProgrammingSequence Types in Python Programming
Sequence Types in Python Programming
 
Python Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, DictionaryPython Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, Dictionary
 
Python Collections
Python CollectionsPython Collections
Python Collections
 
Python Datatypes by SujithKumar
Python Datatypes by SujithKumarPython Datatypes by SujithKumar
Python Datatypes by SujithKumar
 
Pytho_tuples
Pytho_tuplesPytho_tuples
Pytho_tuples
 
Values and Data types in python
Values and Data types in pythonValues and Data types in python
Values and Data types in python
 
arrays of structures
arrays of structuresarrays of structures
arrays of structures
 
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)
 
Chapter 15 Lists
Chapter 15 ListsChapter 15 Lists
Chapter 15 Lists
 
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
 
Chapter 20 generic collections
Chapter 20   generic collectionsChapter 20   generic collections
Chapter 20 generic collections
 
Lists
ListsLists
Lists
 
Java
JavaJava
Java
 
Python Lecture 11
Python Lecture 11Python Lecture 11
Python Lecture 11
 

Viewers also liked

Star2Com Credentials 2016
Star2Com Credentials 2016Star2Com Credentials 2016
Star2Com Credentials 2016
Luca Monticelli
 
Creative commons
Creative commons Creative commons
Creative commons
Jaime Andrés Caro Díaz
 
Brixton Library Technology Initiative Week0 Recap
Brixton Library Technology Initiative Week0 RecapBrixton Library Technology Initiative Week0 Recap
Brixton Library Technology Initiative Week0 Recap
Basil Bibi
 
Data. Insight. Action. Infographics. Where are companies going wrong with dat...
Data. Insight. Action. Infographics. Where are companies going wrong with dat...Data. Insight. Action. Infographics. Where are companies going wrong with dat...
Data. Insight. Action. Infographics. Where are companies going wrong with dat...
Conduit2Loyalty
 
Optical phenomena
Optical phenomenaOptical phenomena
Optical phenomena
Satish Gupta
 
KEVIN GUNZENHAUSER CV MAY 2015
KEVIN GUNZENHAUSER CV MAY 2015KEVIN GUNZENHAUSER CV MAY 2015
KEVIN GUNZENHAUSER CV MAY 2015Kevin Gunzenhauser
 
Elaborate_September Issue
Elaborate_September IssueElaborate_September Issue
Elaborate_September IssueMazin Abusin
 

Viewers also liked (8)

Star2Com Credentials 2016
Star2Com Credentials 2016Star2Com Credentials 2016
Star2Com Credentials 2016
 
New Doc 4_1
New Doc 4_1New Doc 4_1
New Doc 4_1
 
Creative commons
Creative commons Creative commons
Creative commons
 
Brixton Library Technology Initiative Week0 Recap
Brixton Library Technology Initiative Week0 RecapBrixton Library Technology Initiative Week0 Recap
Brixton Library Technology Initiative Week0 Recap
 
Data. Insight. Action. Infographics. Where are companies going wrong with dat...
Data. Insight. Action. Infographics. Where are companies going wrong with dat...Data. Insight. Action. Infographics. Where are companies going wrong with dat...
Data. Insight. Action. Infographics. Where are companies going wrong with dat...
 
Optical phenomena
Optical phenomenaOptical phenomena
Optical phenomena
 
KEVIN GUNZENHAUSER CV MAY 2015
KEVIN GUNZENHAUSER CV MAY 2015KEVIN GUNZENHAUSER CV MAY 2015
KEVIN GUNZENHAUSER CV MAY 2015
 
Elaborate_September Issue
Elaborate_September IssueElaborate_September Issue
Elaborate_September Issue
 

Similar to Brixon Library Technology Initiative

Python-List.pptx
Python-List.pptxPython-List.pptx
Python-List.pptx
AnitaDevi158873
 
8 python data structure-1
8 python data structure-18 python data structure-1
8 python data structure-1
Prof. Dr. K. Adisesha
 
Python for Beginners(v3)
Python for Beginners(v3)Python for Beginners(v3)
Python for Beginners(v3)
Panimalar Engineering College
 
Brixton Library Technology Initiative
Brixton Library Technology InitiativeBrixton Library Technology Initiative
Brixton Library Technology Initiative
Basil Bibi
 
Python Basics it will teach you about data types
Python Basics it will teach you about data typesPython Basics it will teach you about data types
Python Basics it will teach you about data types
NimitSinghal2
 
Pa1 session 3_slides
Pa1 session 3_slidesPa1 session 3_slides
Pa1 session 3_slides
aiclub_slides
 
pythondatatypes.pptx
pythondatatypes.pptxpythondatatypes.pptx
pythondatatypes.pptx
ArchanaAravind1
 
RANDOMISATION-NUMERICAL METHODS FOR ENGINEERING.pptx
RANDOMISATION-NUMERICAL METHODS  FOR ENGINEERING.pptxRANDOMISATION-NUMERICAL METHODS  FOR ENGINEERING.pptx
RANDOMISATION-NUMERICAL METHODS FOR ENGINEERING.pptx
Out Cast
 
Python Programming: Lists, Modules, Exceptions
Python Programming: Lists, Modules, ExceptionsPython Programming: Lists, Modules, Exceptions
Python Programming: Lists, Modules, Exceptions
Sreedhar Chowdam
 
List in Python
List in PythonList in Python
List in Python
Siddique Ibrahim
 
Python lists & sets
Python lists & setsPython lists & sets
Python lists & sets
Aswini Dharmaraj
 
updated_list.pptx
updated_list.pptxupdated_list.pptx
updated_list.pptx
Koteswari Kasireddy
 
Getting started in Python presentation by Laban K
Getting started in Python presentation by Laban KGetting started in Python presentation by Laban K
Getting started in Python presentation by Laban K
GDSCKYAMBOGO
 
Module-2.pptx
Module-2.pptxModule-2.pptx
Module-2.pptx
GaganRaj28
 
Lecture2.pptx
Lecture2.pptxLecture2.pptx
Lecture2.pptx
Sakith1
 
Language R
Language RLanguage R
Language R
Girish Khanzode
 
11 Introduction to lists.pptx
11 Introduction to lists.pptx11 Introduction to lists.pptx
11 Introduction to lists.pptx
ssuser8e50d8
 
Numpy
NumpyNumpy
Numpy
ToniyaP1
 
data structure unit -1_170434dd7400.pptx
data structure unit -1_170434dd7400.pptxdata structure unit -1_170434dd7400.pptx
data structure unit -1_170434dd7400.pptx
coc7987515756
 
arrays.pptx
arrays.pptxarrays.pptx
arrays.pptx
HarmanShergill5
 

Similar to Brixon Library Technology Initiative (20)

Python-List.pptx
Python-List.pptxPython-List.pptx
Python-List.pptx
 
8 python data structure-1
8 python data structure-18 python data structure-1
8 python data structure-1
 
Python for Beginners(v3)
Python for Beginners(v3)Python for Beginners(v3)
Python for Beginners(v3)
 
Brixton Library Technology Initiative
Brixton Library Technology InitiativeBrixton Library Technology Initiative
Brixton Library Technology Initiative
 
Python Basics it will teach you about data types
Python Basics it will teach you about data typesPython Basics it will teach you about data types
Python Basics it will teach you about data types
 
Pa1 session 3_slides
Pa1 session 3_slidesPa1 session 3_slides
Pa1 session 3_slides
 
pythondatatypes.pptx
pythondatatypes.pptxpythondatatypes.pptx
pythondatatypes.pptx
 
RANDOMISATION-NUMERICAL METHODS FOR ENGINEERING.pptx
RANDOMISATION-NUMERICAL METHODS  FOR ENGINEERING.pptxRANDOMISATION-NUMERICAL METHODS  FOR ENGINEERING.pptx
RANDOMISATION-NUMERICAL METHODS FOR ENGINEERING.pptx
 
Python Programming: Lists, Modules, Exceptions
Python Programming: Lists, Modules, ExceptionsPython Programming: Lists, Modules, Exceptions
Python Programming: Lists, Modules, Exceptions
 
List in Python
List in PythonList in Python
List in Python
 
Python lists & sets
Python lists & setsPython lists & sets
Python lists & sets
 
updated_list.pptx
updated_list.pptxupdated_list.pptx
updated_list.pptx
 
Getting started in Python presentation by Laban K
Getting started in Python presentation by Laban KGetting started in Python presentation by Laban K
Getting started in Python presentation by Laban K
 
Module-2.pptx
Module-2.pptxModule-2.pptx
Module-2.pptx
 
Lecture2.pptx
Lecture2.pptxLecture2.pptx
Lecture2.pptx
 
Language R
Language RLanguage R
Language R
 
11 Introduction to lists.pptx
11 Introduction to lists.pptx11 Introduction to lists.pptx
11 Introduction to lists.pptx
 
Numpy
NumpyNumpy
Numpy
 
data structure unit -1_170434dd7400.pptx
data structure unit -1_170434dd7400.pptxdata structure unit -1_170434dd7400.pptx
data structure unit -1_170434dd7400.pptx
 
arrays.pptx
arrays.pptxarrays.pptx
arrays.pptx
 

Recently uploaded

LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
Cheryl Hung
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
UiPathCommunity
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Product School
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
RTTS
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Albert Hoitingh
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
91mobiles
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
Paul Groth
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
Product School
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
Dorra BARTAGUIZ
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Product School
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
Prayukth K V
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
OnBoard
 
Generating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using SmithyGenerating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using Smithy
g2nightmarescribd
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
KatiaHIMEUR1
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
Jemma Hussein Allen
 

Recently uploaded (20)

LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
 
Generating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using SmithyGenerating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using Smithy
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 

Brixon Library Technology Initiative

  • 1. Welcome to the Brixton Library Technology Initiative (Coding for Adults) ZCDixon@lambeth.gov.uk BasilBibi@hotmail.com January 30th 2016 Week 4 – Collections 1
  • 2. Collections • In computer science a collection is a grouping of a variable number of data items (possibly zero) that have some shared significance to the problem being solved and need to be operated upon together in some controlled fashion – Wikipedia • They formally belong to a group of data types called Abstract Data Types.
  • 3. Collections - Data Structures • A data structure is a specialized format for organizing and storing data. General data structure types include the array, the file, the record, the table, the tree, and so on. Any data structure is designed to organize data to suit a specific purpose so that it can be accessed and worked with in appropriate ways. Wikipedia • I will, in fact, claim that the difference between a bad programmer and a good one is whether they consider their code or their data structures more important. – Linus Torvals (my minor change ‘he’ -> ‘they’ – sorry Linus )
  • 4. Kinds of collections • Different kinds of collections are Arrays, Lists, Sets, Trees, Graphs and Maps or Dictionaries. • Fixed-size arrays are usually not considered a collection because they hold a fixed number of data items, although they commonly play a role in the implementation of collections. • Variable-size arrays are generally considered collections.
  • 5. Python Collection Types • In build types : list, set, dict, tuple • collections module adds more : • deque • Counter • OrderedDict : dict subclass that remembers the order entries were added • defaultdict : dict with missing values
  • 6. Arrays, Python arrays and Lists • In most computer languages an array is the simplest form of collection. • It is a sequence of memory positions that can be used to store elements. • Python considers the Array a special kind of List. • The Python List has many very cool features that other languages do not. These might be the reason to write part or the whole of a system in Python.
  • 7. Lists – indexed access A sequence of memory positions that can be used to store elements. # declare a variable myList of type List populated with elements 10 to 50 myList = [10, 20, 30, 40, 50] # Can access the elements using an index. print myList[3] 40 # Index position starts at zero. print myList[0] 10 myList 10 20 30 40 50 index 0 1 2 3 4
  • 8. Lists – indexed access # Can use a variable to index elements in the array or list index = 4 print myList [ index ] 50 # A access from the end using negative index print myList [-1] 50 print myList[-3] 30 myList 10 20 30 40 50 index 0 1 2 3 4 -5 -4 -3 -2 -1
  • 9. Lists – index out of range # We get an IndexError when we try to index out of bounds myList = [10, 20, 30, 40, 50] print myList[ 20 ] IndexError: list index out of range
  • 10. Lists - slices # Lists can be accessed using a ‘slice’ myList = [10, 20, 30, 40, 50] # myList[ start : until ] UNTIL is not included print myList [ 1 : 4 ] [20,30,40] # You can omit implied start and until print myList [ : 4 ] [10,20,30,40] print myList [ 2 : ] [30, 40, 50]
  • 11. Lists - slices # A slice can be defined in steps myList = [10, 20, 30, 40, 50] # myList[ start : until : step ] print myList [ 1 : 4 : 2 ] [20,40] # With implied values for start and end print myList [ : : 2] [10, 30, 50] print myList [ : : 3] [10, 40]
  • 12. Lists – assignment to slices myList = [10,20,30,40,50] # replace some values myList[2:4] = ['C', 'D', 'E'] print myList [10, 20, 'C', 'D', 'E', 50] # now remove them by assigning an empty list to the same positions myList[2:5] = [] print myList [10, 20, 50] # clear the list by replacing all the elements with an empty list myList[:] = [] print myList []
  • 13. Lists – Strings # Strings are treated as a list name = "Felix The House Cat“ print name[2:5] 'lix' # Strings are immutable – you cannot change them : name[2:5] = "CAN NOT DO THIS" TypeError: 'str' object does not support item assignment
  • 14. Lists – basic operation summary Expression Result myList[ 3 ] 40 myList[ 0 ] 10 index=4 myList[ index ] 50 myList[ -1 ] 50 myList[ -3 ] 30 myList[ 20 ] IndexError: list index out of range myList[ 1 : 4 ] [20, 30, 40] myList[ : 4] [10, 20, 30, 40] myList[1:4:2] [20, 40] myList[::2] [10, 30, 50] myList[2:4] = ['C', 'D', 'E‘] [10, 20, 'C', 'D', 'E', 50] myList[2:5] = [] [10, 20, 50] myList[:] = [] [] myList[ : : -1 ] [50,40,30,20,10] Given myList = [10,20,30,40,50]
  • 15. Lists – more operations Expression Result remove(30) [10,20,40,50] index(40) 3 index(99) ValueError: 99 is not in list count(30) 1 append reverse() [50, 40, 30, 20, 10] Given myList = [10,20,30,40,50]
  • 16. Lists – more expressions Python Expression Results len([1, 2, 3]) 3 [1, 2, 3] + [4, 5, 6] [1, 2, 3, 4, 5, 6] ['Hi!'] * 4 ['Hi!', 'Hi!', 'Hi!', 'Hi!'] 3 in [1, 2, 3] True
  • 17. Lists Lists and arrays can be multidimensional. Lists of lists. myMulti = [ [1,2,3], ['a','b','c'], [100,200,300] ] myMulti[ 0 ][ 2 ] 3 myMulti[ 1 ][ 1 ] 'b' myMulti[ 1 ][ 1: ] ['b', 'c']
  • 18. Arrays • Array is different to List because all elements in an array must be the same type • myList = [10, 20, 'C', 'D', 'E', 30, 40, 50] Python docs: https://docs.python.org/2/library/array.html The module defines the following type: class array.array(typecode[, initializer]) A new array whose items are restricted by typecode, and initialized from the optional initializer value, which must be a list, string, or iterable over elements of the appropriate type.
  • 19. Arrays - typecode class array.array(typecode[, initializer]) Type code C Type Python Type Minimum size in bytes 'c' char character 1 'b' signed char int 1 'B' unsigned char int 1 'u' Py_UNICODE Unicode character 2 (see note) 'h' signed short int 2 'H' unsigned short int 2 'i' signed int int 2 'I' unsigned int long 2 'l' signed long int 4 'L' unsigned long long 4 'f' float float 4 'd' double float 8 myFloats = array.array( 'f' , [ 3.1415, 0.6931, 2.7182 ] )
  • 20. Arrays – same type import array myIntArray = array.array('L', [10, 20, 30, 40, 50]) print myIntArray[1] array.array('L', [10, 20, 'C', 'D', 'E', 30, 40, 50]) TypeError: an integer is required
  • 21. Why Is Data Structure Choice Important? Remember what Linus said about the importance of data structures? ... whether they consider their code or their data structures more important ... Let’s see what he means. Consider the differences between a List and an Array.
  • 22. Why Chose List Or Array • In most languages including Python List is implemented as a chain of element positions called a linked list. • Adding to the front of a list is cheap. • Adding to the end of a list is expensive because we have to run along the whole list to find the end and then add the new element. 10 20 30 40
  • 23. Why Chose List Or Array • Inserting an element in a list relatively cheap. • Lists have the memory overhead of all the pointers. 10 20 30 40 A
  • 24. Why Chose List Or Array With arrays we always know the length so adding an element to the end is very cheap. Depending on how arrays are implemented in your language : Inserting is very expensive because we have to take copies of the parts and then glue back together. Adding to the front of an array is very expensive for the same reason. Choosing the right data structure is important .
  • 25. Special list and arrays - Stack, Queue, Deque • A stack is a last in, first out (LIFO) data structure – Items are removed from a stack in the reverse order from the way they were inserted • A queue is a first in, first out (FIFO) data structure – Items are removed from a queue in the same order as they were inserted • A deque is a double-ended queue—items can be inserted and removed at either end
  • 28. Deque – “deck” – Double ended Queue