Using Lists and
Dictionaries
ITS 16163 Introduction to Computer Programming
Using Lists
3
 Lists are sequences, just like tuples, but lists are
mutable. They can be modified. So, lists can do
everything tuples can, plus more. Lists work just like
tuples, so everything you learned about tuples is
applicable to lists.
Example:
inventory = ["sword", "armor", "shield", "healing
potion"]
Lists
(Example Code: lists / Exercise 1)
bracket bracket
4
 You can pass any sequence you want to the len()
function and it will return the length of the sequence.
A sequence’s length is the number of elements it
has.
Example:
print("n You have", len(inventory), "items in your
possession.")
Using the len() Function
(Example Code: lists / Exercise 2)
5
 The in operator works the same with lists as it does
with tuples.
 This creates a condition. If the element is a member, the
condition is true; otherwise, it's false.
Example:
if "healing potion" in inventory:
print("You will live to fight another
day.")
else:
print(“You are doom!")
in operator
(Example Code: lists / Exercise 3)
6
 Once again, the code is exactly the same as it was with
tuples. Indexing a list is the same as indexing a tuple,
just supply the position number of the element you’re
after in brackets.
Example:
index = int(input("n Enter the index number for an
item in inventory: "))
print("At index", index, "is", inventory[index])
Indexing Lists
(Example Code: lists / Exercise 4)
7
 Slicing a list is exactly the same as slicing a tuple!
 you can supply the two end points, separated by a
colon, in brackets:
Example:
start = int(input("nEnter the index number to begin a
slice: "))
finish = int(input("Enter the index number to end the
slice: "))
print("inventory[", start, ":", finish, "] is",
inventory[start:finish] )
Slicing Lists
(Example Code: lists / Exercise 5)
8
 Concatenating lists works the same way concatenating
tuples does.
 you can only concatenate sequences of the same type.
Example:
chest = ["gold", "gems"]
print("You find a chest which contains:")
print(chest)
print("You add the contents of the chest to your
inventory.")
inventory += chest #concatenate chest and
inventory
print("Your inventory is now:")
Concatenating Lists
(Example Code: lists / Exercise 6)
List Mutability
10
 Lists are mutable.
 They can change. As a result, there are many things
you can do with lists that you can’t do with tuples. you
can only concatenate sequences of the same type.
 Because lists are mutable, you can assign an existing
element a new value
Example:
print("You trade your sword for a
crossbow.")
inventory[0] = "crossbow"
print("Your inventory is now:")
print(inventory)
Assigning a New List Element by
Index
(Example Code: lists / Exercise 7)
11
 You can delete an element from a list with delsimply
designate the element after del
Example:
print("In a great battle, your ‘shield’ is
destroyed.")
del inventory[2]
print("Your inventory is now:")
print(inventory)
Deleting a List Element
(Example Code: lists / Exercise 8)
12
SELECTED LIST METHODS
Method Description
append(value) Adds value to end of a list.
sort() Sorts the elements, smallest value
first.
reverse() Reverses the order of a list.
count(value) Returns the number of occurrences of
value.
index(value) Returns the first position number of
where value occurs.
insert(i, value) Inserts value at position i.
pop([i]) Returns value at position i and
removes value from the list.
remove(value) Removes the first occurrence of
value from the list.
(Example Code: high_scores
Dictionaries
14
 Dictionary (or "dict") is a way to store data just like
a list but instead of using only numbers to get the
data, you can use almost anything. This lets you
treat a dict like it's a database for storing and
organizing data.
Example:
stuff = {'name': 'Zed', 'age': 39, 'height': 6 * 12 + 2}
print (stuff ['name'])
print (stuff ['age'])
print (stuff ['height'])
OUTPUT>>> Zed
39
74
Using Dictionaries
(Example Code: dictionaries)
bracket
s
braces braces
SELECTED DIC METHODS
Method Description
len(dict) Gives the total length of the dictionary. This would be equal to
the number of items in the dictionary.
str(dict) Produces a printable string representation of a dictionary
type(variable) Returns the type of the passed variable. If passed variable is
dictionary, then it would return a dictionary type.
dict.clear() Removes all elements of dictionary dict
dict.copy() Returns a shallow copy of dictionary dict
dict.fromkeys() Create a new dictionary with keys from seq and
values set to value.
dict.get(key, default=None) For key key, returns value or default if key not in dictionary
dict.has_key(key) Removed, use the in operation instead.
dict.items() Returns a list of dict's (key, value) tuple pairs
dict.keys() Returns list of dictionary dict's keys
dict.setdefault(key, default =
None)
Similar to get(), but will set dict[key] = default if key is not
already in dict
dict.update(dict2) Adds dictionary dict2's key-values pairs to dict
Source: TutorialsPoints
16
Using Dictionaries (cont.)
Common Questions
What is the difference between a list and a dictionary?
A list is for an ordered list of items. A dictionary (or dict) is for matching some
items (called "keys") to other items (called "values").
What would I use a dictionary for?
When you have to take one value and "look up" another value. In fact you
could call dictionaries "look up tables."
What would I use a list for?
Use a list for any sequence of things that need to be in order, and you only
need to look them up by a numeric index.
(Example Code: geek_translator)

ITS-16163: Module 5 Using Lists and Dictionaries

  • 1.
    Using Lists and Dictionaries ITS16163 Introduction to Computer Programming
  • 2.
  • 3.
    3  Lists aresequences, just like tuples, but lists are mutable. They can be modified. So, lists can do everything tuples can, plus more. Lists work just like tuples, so everything you learned about tuples is applicable to lists. Example: inventory = ["sword", "armor", "shield", "healing potion"] Lists (Example Code: lists / Exercise 1) bracket bracket
  • 4.
    4  You canpass any sequence you want to the len() function and it will return the length of the sequence. A sequence’s length is the number of elements it has. Example: print("n You have", len(inventory), "items in your possession.") Using the len() Function (Example Code: lists / Exercise 2)
  • 5.
    5  The inoperator works the same with lists as it does with tuples.  This creates a condition. If the element is a member, the condition is true; otherwise, it's false. Example: if "healing potion" in inventory: print("You will live to fight another day.") else: print(“You are doom!") in operator (Example Code: lists / Exercise 3)
  • 6.
    6  Once again,the code is exactly the same as it was with tuples. Indexing a list is the same as indexing a tuple, just supply the position number of the element you’re after in brackets. Example: index = int(input("n Enter the index number for an item in inventory: ")) print("At index", index, "is", inventory[index]) Indexing Lists (Example Code: lists / Exercise 4)
  • 7.
    7  Slicing alist is exactly the same as slicing a tuple!  you can supply the two end points, separated by a colon, in brackets: Example: start = int(input("nEnter the index number to begin a slice: ")) finish = int(input("Enter the index number to end the slice: ")) print("inventory[", start, ":", finish, "] is", inventory[start:finish] ) Slicing Lists (Example Code: lists / Exercise 5)
  • 8.
    8  Concatenating listsworks the same way concatenating tuples does.  you can only concatenate sequences of the same type. Example: chest = ["gold", "gems"] print("You find a chest which contains:") print(chest) print("You add the contents of the chest to your inventory.") inventory += chest #concatenate chest and inventory print("Your inventory is now:") Concatenating Lists (Example Code: lists / Exercise 6)
  • 9.
  • 10.
    10  Lists aremutable.  They can change. As a result, there are many things you can do with lists that you can’t do with tuples. you can only concatenate sequences of the same type.  Because lists are mutable, you can assign an existing element a new value Example: print("You trade your sword for a crossbow.") inventory[0] = "crossbow" print("Your inventory is now:") print(inventory) Assigning a New List Element by Index (Example Code: lists / Exercise 7)
  • 11.
    11  You candelete an element from a list with delsimply designate the element after del Example: print("In a great battle, your ‘shield’ is destroyed.") del inventory[2] print("Your inventory is now:") print(inventory) Deleting a List Element (Example Code: lists / Exercise 8)
  • 12.
    12 SELECTED LIST METHODS MethodDescription append(value) Adds value to end of a list. sort() Sorts the elements, smallest value first. reverse() Reverses the order of a list. count(value) Returns the number of occurrences of value. index(value) Returns the first position number of where value occurs. insert(i, value) Inserts value at position i. pop([i]) Returns value at position i and removes value from the list. remove(value) Removes the first occurrence of value from the list. (Example Code: high_scores
  • 13.
  • 14.
    14  Dictionary (or"dict") is a way to store data just like a list but instead of using only numbers to get the data, you can use almost anything. This lets you treat a dict like it's a database for storing and organizing data. Example: stuff = {'name': 'Zed', 'age': 39, 'height': 6 * 12 + 2} print (stuff ['name']) print (stuff ['age']) print (stuff ['height']) OUTPUT>>> Zed 39 74 Using Dictionaries (Example Code: dictionaries) bracket s braces braces
  • 15.
    SELECTED DIC METHODS MethodDescription len(dict) Gives the total length of the dictionary. This would be equal to the number of items in the dictionary. str(dict) Produces a printable string representation of a dictionary type(variable) Returns the type of the passed variable. If passed variable is dictionary, then it would return a dictionary type. dict.clear() Removes all elements of dictionary dict dict.copy() Returns a shallow copy of dictionary dict dict.fromkeys() Create a new dictionary with keys from seq and values set to value. dict.get(key, default=None) For key key, returns value or default if key not in dictionary dict.has_key(key) Removed, use the in operation instead. dict.items() Returns a list of dict's (key, value) tuple pairs dict.keys() Returns list of dictionary dict's keys dict.setdefault(key, default = None) Similar to get(), but will set dict[key] = default if key is not already in dict dict.update(dict2) Adds dictionary dict2's key-values pairs to dict Source: TutorialsPoints
  • 16.
    16 Using Dictionaries (cont.) CommonQuestions What is the difference between a list and a dictionary? A list is for an ordered list of items. A dictionary (or dict) is for matching some items (called "keys") to other items (called "values"). What would I use a dictionary for? When you have to take one value and "look up" another value. In fact you could call dictionaries "look up tables." What would I use a list for? Use a list for any sequence of things that need to be in order, and you only need to look them up by a numeric index. (Example Code: geek_translator)