Data Structures

Data Structures

Strings

So far we have been creating lists that we can modify. This is called mutability (like teenage mutant ninja turtles or X-men because they are changed or mutated). We have already seen lists that cannot change though. Really? Yes, strings are an example of a list that is immutable. You can treat strings exactly like you would lists aside from being able to change the individual characters in the string. You can loop over the characters and get the length len() and even index a string to get a specific character.

'reed'[3] == 'd'

Tuples

Another example of an immutable list is called a tuple. Tuples are just like lists except you can't change them once they are made. You can create a tuple by using parentheses () instead of square brackets [].

my_tuple = (1, 2, 3)

You might wonder why we would ever want to use a tuple instead of a list. Well, they come in handy when you want to give a list to some part of your program but you don't want that part to be able to change it. If you are writing good programs, the various pieces should only know about and be able to modify the parts they own.

Because we might want to limit the amount of control we give to other parts of our programs we sometimes want to convert between lists and tuples. This is easy to do with the list() and tuple() functions supplied by Python.

my_list = [1, 2, 3]
print(type(tuple(my_list))) # <class 'tuple'>

Dictionaries

The dictionaries you are familiar with typically have words and definitions. You can look up a word to find its definition. Well, Python dictionaries are not so different. They have keys and values. The keys are what you use to look up its associated value.

Creating dictionaries is very similar to lists and tuples. You surround the keys and values with curly braces {} and you separate the key from the value with a colon. Key-value pairs are separated with commas.

my_dict = {'1':1, '2':2, '3':3}

To access a specific value you index the dictionary with a value matching a key and the value will be returned.

my_dict['2'] # 2

Try accessing '42' from the previous dictionary!

You should have encountered a KeyError. This is because Python couldn't find the key you asked for in the dictionary. You can check to see if the key exists in the dictionary before you try to access it using some of the operators we mentioned in the previous topic.

if '42' in my_dict:
  favorite_value = my_dict['42']

You can dynamically add items to dictionaries just like we did with lists. You simply do this by indexing the dictionary with a key and setting that key to a specified value.

my_dict['101'] = 'dalmatians'

You can also delete items from a dictionary using the del() function.

del(my_dict['101'])

Last updated