Built-in Data Structures in Python
Lists, Dictionaries, Sets and Tuples
Dept. of CS&E, MSRIT
Motivation
We use lists in our everyday lives—we make shopping
lists, to-do lists, and mental checklists.
Our DNA is essentially a long list of molecules in the
form of a double helix, found in the nucleus of all human
cells and all living organisms.
Its purpose is also to store information—specifically, the
instructions that are used to construct all other cells in the
body—that we call genes .
Given the 2.85 billion nucleotides that make up the
human genome, determining their sequencing (and thus
understanding our genetic makeup) is fundamentally a
computational problem.
Dept. of CS&E, MSRIT
List characteristics
Dept. of CS&E, MSRIT
Lists
A list is a linear data structure
, meaning that its elements have
a linear ordering.
That is, there is a first element,
a second element, and so on.
The values that make up a list
are called its elements, or its
items
Dept. of CS&E, MSRIT
Accessing values in a Lists
Dept. of CS&E, MSRIT
Updating values in a Lists
Dept. of CS&E, MSRIT
List Methods
Dept. of CS&E, MSRIT
To create a List
• The simplest is to enclose the elements in
square brackets [ and ]:
• The elements of a list don’t have to be the
same type.
Dept. of CS&E, MSRIT
List Methods Example
Dept. of CS&E, MSRIT
Answer this?
Dept. of CS&E, MSRIT
Append vs Extend
• nums.append([6,7,8]) • nums.extend([6,7,8])
Dept. of CS&E, MSRIT
Append vs Extend
• “extend” takes a single argument, which is always
a list, and adds each of the elements of that list to
the original list.
• ”append” takes one argument, which can be any
data type, and simply adds it to the end of the list.
Dept. of CS&E, MSRIT
List Concatenation
Dept. of CS&E, MSRIT
List Slices
• a[start:end]
– # items start through end-1
• a[start:]
– # items start through the rest of the array
• a[:end]
– # items from the beginning through end-1
• a[:]
– # a copy of the whole array
• a[start:end:step]
– # start through not past end, by step
Dept. of CS&E, MSRIT
List Slices Example
Dept. of CS&E, MSRIT
List Slices Example
• Negative List Indices accesses elements from the
end of the list counting backwards. The last element
of any non-empty list is always li[-1]
>>> li= ['a', 'b', 'mpilgrim', 'z', 'example']
>>> li[-1] returns 'example'
>>> li[-3] returns 'mpilgrim‘
• Slicing Shorthand
>>> li[:3] returns ['a', 'b', 'mpilgrim']
>>> li[3:] returns ['z', 'example']
>>> li[:] returns ['a', 'b', 'mpilgrim', 'z', 'example']
Dept. of CS&E, MSRIT
Deleting List Elements
>>> a = [-1, 1, 66.25, 333, 333, 1234.5]
>>> del a[0]
>>> a
[1, 66.25, 333, 333, 1234.5]
>>> del a[2:4]
>>> a
[1, 66.25, 1234.5]
>>> del a[:]
>>> a
[]
Dept. of CS&E, MSRIT
Removing List Elements
• “remove” removes the first occurrence of a value
from a list.
• If the value is not found in the list it raises an
exception.
• Pop does two things: it removes the last
element of the list, and it returns the value that
it removed. Note that this is different from li[-1],
which returns a value but does not change the list,
and different from li.remove(value), which
changes the list but does not return a value.
Dept. of CS&E, MSRIT
Removing List Elements
>>> li = ['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new',
'two', 'elements']
>>> li.remove("z")
>>> li = ['a', 'b', 'new', 'mpilgrim', 'example', 'new', 'two',
'elements']
>>> li.remove("new")
>>> li = ['a', 'b', 'mpilgrim', 'example', 'new', 'two',
'elements']
>>> li.remove("c")
Traceback (innermost last): File "<interactive input>", line 1, in ? ValueError:
list.remove(x): x not in list
>>> li.pop()
'elements'
>>> li ['a', 'b', 'mpilgrim', 'example', 'new', 'two']
Dept. of CS&E, MSRIT
Searching List Elements
index finds the first occurrence of a value in the list and
returns the index.
>>> li = ['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new',
'two', 'elements']
>>> li.index("example")
5
>>> li.index("new")
2
>>> li.index("c")
Traceback (innermost last): File "<interactive input>", line 1, in ?
ValueError: list.index(x): x not in list
>>> "c" in li
False
Dept. of CS&E, MSRIT
Built in List Functions
Dept. of CS&E, MSRIT
Built in List Functions
Dept. of CS&E, MSRIT
Iterating over Lists in Python
• For Loops
• While loop
Dept. of CS&E, MSRIT
Iterating over Lists in Python
# You can either use loops:
squares = []
for x in range(10):
squares.append(x**2)
print squares
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
# Or you can use list comprehensions to get
the same result:
squares = [x**2 for x in range(10)]
print squares
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Dept. of CS&E, MSRIT
Iterating over Lists in Python
listOfWords = ["this","is","a","list","of","words"]
items = [ word[0] for word in listOfWords]
print (items)
Output: ['t', 'i', 'a', 'l', 'o', 'w']
string = "Hello 12345 World"
numbers = [x for x in string if x.isdigit()]
print (numbers)
Output: ['1', '2', '3', '4', '5‘]
Dept. of CS&E, MSRIT
Answer this?
Dept. of CS&E, MSRIT
Iterating Over List Elements vs. List Index Values
• Iterating Over List • List Index
Elements Values
Dept. of CS&E, MSRIT
Tuples
• A tuple is an immutable linear data
structure. Thus, in contrast to lists, once a
tuple is defined, it cannot be altered.
• The syntax for declaring tuples in Python
is given below.
– tuples are denoted by parentheses instead of
square brackets
Dept. of CS&E, MSRIT
Tuples Example
Dept. of CS&E, MSRIT
Tuples
• The empty tuple is written as two parentheses
containing nothing:
tup1 = ()
• To write a tuple containing a single value you have
to include a comma, even though there is only one
value:
tup1 = (50,)
• Like string indices, tuple indices start at 0, and
tuples can be sliced, concatenated and so on.
Dept. of CS&E, MSRIT
Updating Tuples
• Tuples are immutable which means you cannot
update them or change values of tuple elements.
But we able to take portions of an existing tuples
to create a new tuples as follows. Following is a
simple example:
Dept. of CS&E, MSRIT
Deleting Tuple elements
• Removing individual tuple elements is not
possible. There is, of course, nothing wrong with
putting together another tuple with the undesired
elements discarded.
• To explicitly remove an entire tuple, just use the
del statement. This produce the error as after “del
tup” tuple does not exist any more
Dept. of CS&E, MSRIT
Set
• A set is a mutable data type with
nonduplicate, unordered values,
providing the usual mathematical set
operations.
• The syntax for declaring sets in Python is
given below.
A={1,2,3,4}
Dept. of CS&E, MSRIT
Set Methods
Dept. of CS&E, MSRIT
Self Test Questions
• For set ‘s ‘ containing values 1, 2, 3, and set ‘t’
containing 3, 4, 5, which of the following are the
correct results for each given set operation?
– (a) s | t ➝
– (b) s & t ➝
– (c) s - t ➝
Dept. of CS&E, MSRIT
Self Test Questions
• 1. Which of the following sequence types is a mutable type?
– (a) strings (b) lists (c) tuples
• 2. Which of the following is true?
– (a) Lists and tuples are denoted by the use of square brackets.
– (b) Lists are denoted by use of square brackets and tuples are denoted by the
use of parentheses.
– (c) Lists are denoted by use of parentheses and tuples are denoted by the
use of square brackets.
• 3. Lists and tuples must each contain at least one element.
(TRUE/FALSE)
• 4. For lst = [4, 2, 9, 1], what is the result of the following
operation, lst.insert(2, 3)?
– (a) [4, 2, 3, 9, 1] (b) [4, 3 ,2, 9, 1] (c) [4, 2, 9, 2, 1]
Dept. of CS&E, MSRIT
Dictionary
• A dictionary is a mutable, associative
data structure of variable length.
• The syntax for declaring dictionaries in
Python is given below.
daily_temps = {'sun': 68.8, 'mon': 70.2, 'tue': 67.2, 'wed': 71.8}
Key Value
Dept. of CS&E, MSRIT
Dictionary
• A dictionary is mutable and is another container type that
can store any number of Python objects, including other
container types.
• Dictionaries consist of pairs (called items) of keys and
their corresponding values.
• Python dictionaries are also known as associative arrays
or hash tables.
• Keys are unique within a dictionary while values may
not be.
• The values of a dictionary can be of any type, but the
keys must be of an immutable data type such as strings,
numbers, or tuples.
Dept. of CS&E, MSRIT
Dictionary
• The syntax for declaring dictionaries in Python
is given below.
daily_temps = {'sun': 68.8, 'mon': 70.2, 'tue': 67.2, 'wed': 71.8}
Key Value
• The syntax for accessing an element of a dictionary is the
same as for accessing elements of sequence types, except
that a key value is used within the square brackets instead
of an index value:
daily_temps['sun']
Key
Dept. of CS&E, MSRIT
Updating Dictionary
Dept. of CS&E, MSRIT
Deleting Dictionary elements
Dept. of CS&E, MSRIT
Properties of dictionary Keys
• More than one entry per key not allowed. Which means no
duplicate key is allowed. When duplicate keys encountered
during assignment, the last assignment wins.
• Keys must be immutable. Which means you can use
strings, numbers, or tuples as dictionary keys but
something like ['key'] is not allowed..
• Dictionary Keys Are Case-Sensitive
Dept. of CS&E, MSRIT
Dictionary Methods
• dict.items()
– Returns a list of dict's (key, value) tuple pairs.
• dict.keys()
– Returns list of dictionary dict's keys
• dict.values()
– Returns list of dictionary dict's values
• dict.update(dict2)
– Adds dictionary dict2's key-values pairs to dict
Dept. of CS&E, MSRIT
Dictionary fromKeys( ) method
• The method fromkeys() creates a new dictionary with keys
from seq and values set to value.
dict.fromkeys(seq[, value]))
• seq -- This is the list of values which would be used for
dictionary keys preparation.
• value -- This is optional, if provided then value would be
set to this value
Dept. of CS&E, MSRIT
Dictionary get( ) method
• The method get() return a value for the given key.
If key is not available then returns default value
None.
dict.get(key, default=None)
Dept. of CS&E, MSRIT
in Operator in dictionary
• ‘in’ operator to test whether the dictionary had a
certain key
• Example
dict={1:’a’,2:’b’,3:’c’}
>>> 1 in dict
>>> true
Dept. of CS&E, MSRIT
Examples and Exercises
• Access the 03_Day Directive
Dept. of CS&E, MSRIT