Introduction to Business Analytics
Copyright © LEARNXT
Introduction to Python Programming
Lists, Tuples & Dictionaries
Copyright © LEARNXT
Objectives
At the end of this topic, you will be able to understand and explain:
Understand the fundamentals of data types in Python
Explain the basics and creation of lists with examples
Explain the process of indexing and slicing lists
Explain how to create Tuples and Dictionaries with examples
Describe functions for working with Collections
Copyright © LEARNXT
Data Types in Python
Copyright © LEARNXT
Data Types
Every value in Python has a datatype
Since everything is an object in Python programming, data types are classes and variables are
instance (object) of these classes
Data types are the classification or categorization of data items
They represent a kind of value which determines what operations can be performed on that
data
Copyright © LEARNXT
Data Types
We saw some of the basic data types in an earlier session: Numeric (Integer and Float), String
and Boolean (true/false) are the most used data types
In this session, we will look at three more data types
Data Types
Lists Tuples Dictionaries
Copyright © LEARNXT
Types – Lists, Tuples & Dictionaries
Data Lists Tuples
Dictionary
Copyright © LEARNXT
Lists
Copyright © LEARNXT
Lists
Lists are ordered and have a definite count
A single list may contain integers, floats, strings, other lists, as well as Objects
Lists are mutable - they can be altered even after their creation
Created by just placing the sequence inside square brackets[]
Imagine a horizontal bookshelf with elements in it
Copyright © LEARNXT
Lists
The elements are indexed according to a sequence
Indexing is done with 0 being the first index
Example:
INDEX 0 1 2 3 4 5 6 7
ELEMENT 32 45 171.3 23 20 3 945 221
Copyright © LEARNXT
Lists
# Create simple lists
List = [1, 3, 5, 7, 11]
List
[1, 3, 5, 7, 11]
list1 = [0, 1, 'boom’]
[0, 1, 'boom']
Copyright © LEARNXT
Lists
# Check type of the list created above
type(list1)
list
# Create an empty list
x = []
x
[]
Copyright © LEARNXT
Lists - Append
# Create a list and append to it
y = [1,2,3]
print(y)
[1, 2, 3]
y.append("done")
print(y)
[1, 2, 3, 'done']
Copyright © LEARNXT
Nested Lists
Lists contain object references and can be nested
a = [0,1,2]
print(a)
[0, 1, 2]
b = [a,3,4]
print(b)
[[0, 1, 2], 3, 4]
Copyright © LEARNXT
Lists using range()
# Create a list using range() - one argument
y = list(range(8))
print(y)
[0, 1, 2, 3, 4, 5, 6, 7]
# Create a list using range() - two arguments
z = list(range(1,9))
print(z)
[1, 2, 3, 4, 5, 6, 7, 8]
Copyright © LEARNXT
Lists using range()
# Create a list using range() - three arguments
w = list(range(100,111, 2))
print(w)
[100, 102, 104, 106, 108, 110]
Copyright © LEARNXT
Indexing and Slicing Lists
Copyright © LEARNXT
Indexing Lists – Using Brackets [ ]
w = [‘a’, ’b’, ’c’, ’d’, ’e’]
print(w)
['a', 'b', 'c', 'd', 'e']
# Indexing in list
w[0]
‘a’
w[4]
‘e’
Copyright © LEARNXT
Indexing Lists – Using Brackets [ ]
Check length of the list
# Length of w
len(w)
5
Negative indexation can also be applied
Copyright © LEARNXT
Indexing Lists – Using Negative Indexation
# Using negative indexation in list
# Retrieve elements using index positions -5 and -1
w[-5]
‘a’
['a', 'b', 'c', 'd', 'e']
w[-1]
'e'
Copyright © LEARNXT
Modify Values in a List Using Indexing
# Create a list
w = [‘a’, ’b’, ’c’, ’d’, ’e’]
w[4]
‘e’
# Change the value at index position 4
w[4]= 23
print(w)
['a', 'b', 'c', 'd', 23]
Copyright © LEARNXT
Slicing Lists
Slicing starts with : list1[2:7]
Value on left and value on right of colon indicate start and stop index values list1[:]
No value on either side: it assumes slicing the whole set
INDEX 0 1 2 3 4 5 6 7
ELEMEN 32 45 171.3 23 20 3 945 221
T
Indexing: Indexing is used to obtain individual elements
Slicing: Slicing is used to obtain a sequence of elements
Indexing and Slicing can be done in Python Sequences types like list, string, tuple,
range objects
Copyright © LEARNXT
Slicing Lists
# Create a list
xlist = [‘A’, ‘B’, ‘C’, ‘D’, ‘E’, ‘F’, ‘G’, ‘H’]
INDEX 0 1 2 3 4 5 6 7
ELEMENT A B C D E F G H
Note that [2:7] slicing starts at
# Slicing a list index position 2 but ends at
index position 6 and not 7
xlist[2:7]
[‘C’, ‘D’, ‘E’, ‘F’, ‘G’]
INDEX 0 1 2 3 4 5 6 7
ELEMENT A B C D E F G H
Copyright © LEARNXT
Slicing Lists
xlist = [‘A’, ‘B’, ‘C’, ‘D’, ‘E’, ‘F’, ‘G’, ‘H’]
INDEX 0 1 2 3 4 5 6 7
ELEMENT A B C D E F G H
# Slice the whole list (no subsetting)
xlist[:]
[‘A’, ‘B’, ‘C’, ‘D’, ‘E’, ‘F’, ‘G’, ‘H’]
# Slice the list and select every second element (include third argument)
xlist[0:7:2]
Copyright © LEARNXT
[A’, ‘C’, ‘E’, ‘G’]
Slicing Lists
xlist = [‘A’, ‘B’, ‘C’, ‘D’, ‘E’, ‘F’, ‘G’, ‘H’]
INDEX 0 1 2 3 4 5 6 7
ELEMENT A B C D E F G H
# Reverse index slicing
xlist[6:0:-1]
['G', 'F', 'E', 'D', 'C', 'B’]
xlist[6:0:-2]
Copyright © LEARNXT
['G', 'E', 'C']
Indexing and Slicing Lists – Using Functions
# Create a list and print it
x=[1,3,5,7,11]
print (x)
[1, 3, 5, 7, 11]
# Indexing the list within print function
print ("x[2]=",x[2])
x[2]= 5
x[2] = 0
print ("Replace 5 with 0, x = ", x)
Replace 5 with 0, x = [1, 3, 0, 7, 11]
Copyright © LEARNXT
Indexing and Slicing Lists – Using Functions
# Add an element to the list using append()
x.append(13)
print ("After append, x = ", x)
After append, x = [1, 3, 0, 7, 11, 13]
# Remove an element from the list using remove()
x.remove(1) # removes the item 1, not the item at position 1
print ("After remove item 1, x = ", x)
After remove item 1, x = [3, 0, 7, 11, 13]
Copyright © LEARNXT
Indexing and Slicing Lists – Using Functions
# Add an element at a specific index position
x.insert(1,42)
print ("Insert 42 at index position 1, x = ", x)
Insert 42 at index position 1, x = [3, 42, 0, 7, 11, 13]
Copyright © LEARNXT
+= Operator for Adding to Lists
a = [1, 3, 5]
print(a)
[1, 3, 5]
# Using += operator to add to a list - Examples
a += [7] # a += 7 fails
print(a)
[1, 3, 5, 7]
a += [“the-end”]
print(a)
1, 3, 5, 7, 'the-end']
Copyright © LEARNXT
Tuples and Dictionaries
Copyright © LEARNXT
Tuples
Tuples are a collection of data items. They may be of different types
Tuples are immutable like strings. Lists are like tuples but are mutable
Python uses () to denote tuples; if we have only one item, we need to use a comma to indicate
it's a tuple: (“Tony”,).
An empty tuple is denoted by ()
Need to enclose tuple in () if we want to pass it all together as one argument to a function
Copyright © LEARNXT
Tuples - Example
# Create a tuple and print it
tuple1 = (“Tony”, “Pat”, “Stewart”)
print(tuple1)
('Tony', 'Pat', 'Stewart’)
Copyright © LEARNXT
Tuples - Example
# Mixed types within a tuple
tuple2 = (1, 5, "George", 87.76, True)
print(tuple2)
(1, 5, 'George', 87.76, True)
Copyright © LEARNXT
Dictionaries
Unordered collections where items (values) are accessed by a key, not by the position in the
list
Use flower brackets - {}
No ordering is applicable here, unlike lists
Collection of arbitrary objects; use object references like lists
Nestable
Concatenation, slicing, and other operations that depend on the order of elements do not work
on dictionaries
Copyright © LEARNXT
Dictionary Creation Key
# Create a dictionary
jobs = {'David':'Professor', 'Sahan':'Postdoc', 'Shawn':'Grad student’}
Value
# Print the dictionary
jobs
{'David': 'Professor', 'Sahan': 'Postdoc', 'Shawn': 'Grad student’}
# View data type for the dictionary
type(jobs)
dict
Copyright © LEARNXT
Dictionary – Indexation & Assigning Value
# Create a dictionary
jobs = {'David':'Professor', 'Sahan':'Postdoc', 'Shawn':'Grad student’}
# Indexing the dictionary
jobs['Sahan’]
'Postdoc’
# Can change in place – assign a different value to key
jobs['Shawn'] = 'Postdoc’
jobs['Shawn’]
'Postdoc'
Copyright © LEARNXT
Dictionary – Accessing Keys, Values & Items
# Keys
jobs.keys()
dict_keys(['David', 'Sahan', 'Shawn']) # note order can be different
# Values
jobs.values()
dict_values(['Professor', 'Postdoc', 'Postdoc’])
# Items in the dictionary
jobs.items()
dict_items([('David', 'Professor'), ('Sahan', 'Postdoc'), ('Shawn', 'Postdoc')])
Copyright © LEARNXT
Common Dictionary Operations
Delete an entry (by key)
Syntax:
del d['keyname’]
Add an entry
Syntax:
d['newkey'] = ‘newvalue’
See if a key is in dictionary
'keyname' in d
Copyright © LEARNXT
Common Dictionary Operations
get() method useful to return value but not fail (return None) if key doesn't exist (or can provide
a default value)
Syntax:
d.get('keyval', default)
Copyright © LEARNXT
Dictionary Operations - Examples
# Create a new dictionary
dict2 = {'Bat1':'Rohit', 'Bat2':'Dhawan', 'Bat3':'Virat', 'Wk’: 'Dhoni', 'Bowl1': 'Bumrah', 'Bowl2': 'Shami',
'Bowl3': 'Chahal'}
print(dict2)
{'Bat1': 'Rohit', 'Bat2': 'Dhawan', 'Bat3': 'Virat', 'Wk': 'Dhoni', 'Bowl1': 'Bumrah', 'Bow2': 'Shami', 'Bowl3':
'Chahal’}
# Delete an entry by key
del dict2['Bat1’]
print(dict2)
{'Bat2': 'Dhawan', 'Bat3': 'Virat', 'Wk': 'Dhoni', 'Bowl1': 'Bumrah', 'Bow2': 'Shami', 'Bowl3': 'Chahal'}
Copyright © LEARNXT
Dictionary Operations - Examples
# Add an entry by key
dict2['Wk2'] = 'Pant’
print(dict2)
{'Bat2': 'Dhawan', 'Bat3': 'Virat', 'Wk': 'Dhoni', 'Bowl1': 'Bumrah', 'Bow2': 'Shami', 'Bowl3': 'Chahal', 'Wk2': 'Pant’}
# See if a key is in dictionary
'Wk' in dict2
True
'Umpire' in dict2
False
Copyright © LEARNXT
Dictionary Operations - Examples
# get method useful to return value but not fail if key doesn't exist
dict2.get('Bat3', 'Not in team’)
‘Virat’
dict2.get('Bat5', 'Not in team’)
'Not in team’
Copyright © LEARNXT
Dictionary Example Using for Loop
# Create a Dictionary
bookauthors = {'Gone with the Wind': 'Margaret Mitchell’, 'Aeneid': 'Virgil‘, 'Odyssey': 'Homer'}
print(bookauthors)
{'Gone with the Wind': 'Margaret Mitchell', 'Aeneid': 'Virgil', 'Odyssey': 'Homer’}
# Check type of variable
type(bookauthors)
dict
Copyright © LEARNXT
Dictionary Example Using for Loop
# Dictionary using for loop
for book in bookauthors:
print (book, 'by', bookauthors[book])
Gone with the Wind by Margaret Mitchell
Aeneid by Virgil
Odyssey by Homers
Copyright © LEARNXT
Constructing Dictionaries from Lists
If we have separate lists for the keys and values, we can combine them into a dictionary using
the zip function and a dict constructor:
# Create simple lists for keys and values
keys = ['david', 'chris', 'stewart’]
values = ['504', '637', '921’]
print(keys)
print(values)
['david', 'chris', 'stewart’]
['504', '637', '921’]
Copyright © LEARNXT
Constructing Dictionaries from Lists
# Create Dictionary from lists using zip and dict
newdict = dict(zip(keys, values))
print(newdict)
{'david': '504', 'chris': '637', 'stewart': '921'}
Copyright © LEARNXT
Working with Collections
Copyright © LEARNXT
Length of Collections
len() returns the length of a tuple, list, or dictionary or the number of characters of a string
# length of a dictionary
newdict = {'david': '504', 'chris': '637', 'stewart': '921’}
len(newdict)
3
len('david’)
5
len(‘stewart')
7
Copyright © LEARNXT
“in” Operator
For collection data types, the “in” operator determines whether something is a
member of the collection (and “not in” tests if not a member):
team = ("David", "Robert", "Paul")
"Howell" in team
False
"Stewart" not in team
True
Copyright © LEARNXT
Iteration: for ... in
To traverse a collection type, use for ... in
numbers = (1, 2, 3)
for i in numbers:
print (i)
1
2
3
Copyright © LEARNXT
Copying Collections
Using assignment just makes a new reference to the same collection
# Assign the values in A to B
A = [0,1,3]
B=A
B[1] = 25
print(B)
[0,25,3]
print(A)
[0,25,3]
Copyright © LEARNXT
Copying Collections
So, use copy() to create a new collection and modify the new collection
# Copy the values in A to C
A = [0,1,3]
C = A.copy() # make a copy
C[2] = 99 # Change a value in C
print(C)
[0,1,99]
print(A)
[0,1,3] # Value of A is not changed since we created a copy of
Copyright © LEARNXT
the original collection A
Summary
Data types are the classification or categorization of data items. They represent a kind of value
which determines what operations can be performed on that data
Lists are ordered and have a definite count. A single list may contain integers, floats, strings,
other lists, as well as Objects
We index a list to obtain individual elements and slice a list to get a sequence of elements
Tuples are a collection of data items and are immutable
Dictionaries are unordered collections where items (values) are accessed by a key, not by the
position in the list
In order to ensure that you don’t change values in a parent collection, you need to copy a
collection instead of assigning it to another variable
Copyright © LEARNXT
Additional Resources
McKinney, W. (2013). Python for data analysis. O'Reilly Media.
Lutz, M. (2013). Learning Python: Powerful object-oriented programming. O'Reilly Media.
Summerfield, M. (2010). Programming in Python 3: A complete introduction to the Python
language. Pearson Education India.
Matthes, E. (2019). Python crash course: A hands-on, project-based introduction to
programming (2nd ed.). No Starch Press.
Beazley, D., & Jones, B. K. (2013). Python cookbook: Recipes for mastering Python 3. O'Reilly
Media.
Copyright © LEARNXT
e-References
Welcome to Python.org. (n.d.). Python.org. https://www.python.org
Introduction to Python. (n.d.). W3Schools Online Web
Tutorials. https://www.w3schools.com/python/python_intro.asp
Copyright © LEARNXT 55
Any Questions?
Thank you
Copyright © LEARNXT
Copyright © LEARNXT