Lists and dictionaries

If you’re in Year 11 or above you’ll know what lists are…or you should have done Computing. Your loss. Or you did do Computing and weren’t listening. Your loss.

So a list you can create like so:

myList = [4, 8, 12]

Nice and easy. You can then access the first item of the list like so:

print(myList[0])

So each item is numbered from 0. No problem. If you remove item 0, then the item in the next slot becomes item 0.

print(myList[0])
# Prints 4
myList.pop(0)
# Removes the first item of the list
print(myList[0])
# Prints 8

You can see that a list has a definite order. In the original list 4 is the first item and 12 is the last item.

Dictionaries don’t give a ____ about order. They are agents of chaos!!! Or hash tables. You should have covered hash tables in year 12. If you haven’t covered hash tables, they’re probably not what you’re thinking they are, but we can still move on.

You can create a dictionary with curly brackets instead, but they need to be a pair of items.

myDict = {0: 4, 1: 8, 2: 12}

So you can see that item 0 has been assigned the value of 4. That is it’s value, it will not change (unless you explicitly change it).

print(myDict[0])
# Prints 4
del myDict[0]
# Removes first element
print(myDict[0])
# Key error - there is no myDict[0], you just deleted it.
print(myDict[1])
# This would print 8, provided you hadn't already broken the code and hit a runtime error in the line before.

The reasoning of this is that the dictionary is using a hash table to store the data, and it’s therefore got no intrinsic order. Whereas a list is an ordered list of one item followed by another. Different tools for different uses.

Leave a Reply

Your email address will not be published. Required fields are marked *