Python - Data Types (List, Tuple, Dictionary)
Python - Data Types (List, Tuple, Dictionary)
Copyright © LEARNXT
Introduction to Python Programming
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
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
Data Types
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
Copyright © LEARNXT
Lists
The elements are indexed according to a sequence
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]
[0, 1, 'boom']
Copyright © LEARNXT
Lists
# Check type of the list created above
type(list1)
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]
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)
Copyright © LEARNXT
Indexing and Slicing Lists
Copyright © LEARNXT
Indexing Lists – Using Brackets [ ]
w = [‘a’, ’b’, ’c’, ’d’, ’e’]
print(w)
# 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
Copyright © LEARNXT
Indexing Lists – Using Negative Indexation
# Using negative indexation in list
w[-5]
‘a’
'e'
Copyright © LEARNXT
Modify Values in a List Using Indexing
# Create a list
‘e’
w[4]= 23
print(w)
Value on left and value on right of colon indicate start and stop index values list1[:]
Copyright © LEARNXT
Slicing Lists
# Create a list
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
xlist[:]
# 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
xlist[6:0:-1]
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]
print ("x[2]=",x[2])
x[2]= 5
x[2] = 0
print ("Replace 5 with 0, x = ", x)
Copyright © LEARNXT
Indexing and Slicing Lists – Using Functions
# Add an element to the list using append()
x.append(13)
print ("After append, x = ", x)
x.insert(1,42)
print ("Insert 42 at index position 1, x = ", x)
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”,).
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
print(tuple1)
Copyright © LEARNXT
Tuples - Example
# Mixed types within a tuple
print(tuple2)
Copyright © LEARNXT
Dictionaries
Unordered collections where items (values) are accessed by a key, not by the position in the
list
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
type(jobs)
dict
Copyright © LEARNXT
Dictionary – Indexation & Assigning Value
# Create a dictionary
jobs['Sahan’]
'Postdoc’
jobs['Shawn'] = 'Postdoc’
jobs['Shawn’]
'Postdoc'
Copyright © LEARNXT
Dictionary – Accessing Keys, Values & Items
# Keys
jobs.keys()
# Values
jobs.values()
jobs.items()
Copyright © LEARNXT
Common Dictionary Operations
Delete an entry (by key)
Syntax:
del d['keyname’]
Add an entry
Syntax:
d['newkey'] = ‘newvalue’
'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’}
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’}
'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
‘Virat’
'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’}
type(bookauthors)
dict
Copyright © LEARNXT
Dictionary Example Using for Loop
# Dictionary using for loop
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:
print(keys)
print(values)
print(newdict)
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
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):
False
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
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
A = [0,1,3]
print(C)
[0,1,99]
print(A)
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
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.
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
Copyright © LEARNXT 55
Any Questions?
Thank you
Copyright © LEARNXT
Copyright © LEARNXT