CommonLounge Archive

Python: Variables, Lists and Dictionaries

August 04, 2018

In the last tutorial, you learnt about Python Basics: Numbers, Strings and Functions. In this tutorial, you’ll learn about variables, lists and dictionaries. In the process, you’ll also see how to print values stored in variables.

Variables

An important concept in programming is variables. A variable is nothing more than a name for something so you can use it later. Programmers use these variables to store data, make their code more readable and so they don’t have to keep remembering what things are.

Let’s say we want to create a new variable called name:

>>> name = "Commonlounge"

We type name equals "Commonlounge".

As you’ve noticed, your program didn’t return anything like it did before. So how do we know that the variable actually exists? Simply enter name and hit enter:

>>> name
'Commonlounge'

Yippee! Your first variable! :) You can always change what it refers to:

>>> name = "Dave"
>>> name
'Dave'

You can use it in functions too:

>>> len(name)
5

Awesome, right? Of course, variables can be anything – numbers too! Try this:

>>> a = 4
>>> b = 6
>>> a * b
24

But what if we used the wrong name? Can you guess what would happen? Let’s try!

>>> city = "Tokyo"
>>> ctiy
Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'ctiy' is not defined

An error! As you can see, Python has different types of errors and this one is called a NameError. Python will give you this error if you try to use a variable that hasn’t been defined yet. If you encounter this error later, check your code to see if you’ve mistyped any names.

Play with this for a while and see what you can do!

The print command

Try this:

>>> name = 'Maria'
>>> name
'Maria'
>>> print name 
Maria

When you just type name, the Python interpreter responds with the string representation of the variable name, which is the letters M-a-r-i-a, surrounded by single quotes, ''. When you say print name, Python will “print” the contents of the variable to the screen, without the quotes, which is neater.

As we’ll see later, the print command is also useful when we want to print things from inside functions, or when we want to print things on multiple lines.

Lists

Beside strings and integers, Python has all sorts of different types of objects. Now we’re going to introduce one called list. Lists are exactly what you think they are: objects which are lists of other objects. :)

Go ahead and create a list:

>>> []
[]

Yes, this list is empty. Not very useful, right? Let’s create a list of lottery numbers. We don’t want to repeat ourselves all the time, so we will put it in a variable, too:

>>> lottery = [3, 42, 12, 19, 30, 59]

All right, we have a list! What can we do with it? Let’s see how many lottery numbers there are in a list. Do you have any idea which function you should use for that? You know this already!

>>> len(lottery)
6

Yes! len() can give you a number of objects in a list. Handy, right? Maybe we will sort it now:

>>> lottery.sort()

This doesn’t return anything, it just changed the order in which the numbers appear in the list. Let’s print it out again and see what happened:

>>> print lottery
[3, 12, 19, 30, 42, 59]

As you can see, the numbers in your list are now sorted from the lowest to highest value. Congrats!

Maybe we want to reverse that order? Let’s do that!

>>> lottery.reverse()
>>> print lottery
[59, 42, 30, 19, 12, 3]

We can also concatenate two lists (just like strings):

>>> [1, 2] + [2, 3]
[1, 2, 2, 3]
>>> lottery + [37, 81, 56]
[59, 42, 30, 19, 12, 3, 37, 81, 56]

or repeat a list (again, just like strings):

>>> [1, 2]*4
[1, 2, 1, 2, 1, 2, 1, 2]
>>> lottery*2
[59, 42, 30, 19, 12, 3, 59, 42, 30, 19, 12, 3]

If you want to add a single element to your list, you can do this by typing this command:

>>> lottery.append(199)
>>> print lottery
[59, 42, 30, 19, 12, 3, 199]

If you want to show only the first number, you can do this by using indexes. An index is the number that says where in a list an item occurs. Programmers prefer to start counting at 0, so the first object in your list is at index 0, the next one is at 1, and so on. Try this:

>>> print lottery[0]
59
>>> print lottery[1]
42

As you can see, you can access different objects in your list by using the list’s name and the object’s index inside of square brackets.

To delete something from your list you will need to use indexes as we learned above and the pop()method. Let’s try an example and reinforce what we learned previously; we will be deleting the first number of our list.

>>> print lottery 
[59, 42, 30, 19, 12, 3, 199]
>>> print lottery[0]
59
>>> lottery.pop(0)
59
>>> print lottery
[42, 30, 19, 12, 3, 199]

That worked like a charm!

For extra fun, try some other indexes: 6, 7, 1000, -1, -6 or -1000. See if you can predict the result before trying the command. Do the results make sense?

You can find a list of all available list methods in this chapter of the Python documentation: Data Structures — Python 2.7.15 documentation

Dictionaries

A dictionary is similar to a list, but you access values by looking up a key instead of a numeric index. A key can be any string or number. The syntax to define an empty dictionary is:

>>> {}
{}

This shows that you just created an empty dictionary. Hurray!

Now, try writing the following command (try substituting your own information, too):

>>> participant = {'name': 'Commonlounge', 'country': 'Canada', 'favorite_numbers': [7, 42, 92]}

With this command, you just created a variable named participant with three key–value pairs:

  • The key name points to the value 'Commonlounge' (a string object),
  • country points to 'Canada' (another string),
  • and favorite_numbers points to [7, 42, 92] (a list with three numbers in it).

You can check the content of individual keys with this syntax:

>>> print participant['name']
Commonlounge

See, it’s similar to a list. But you don’t need to remember the index – just the name.

What happens if we ask Python the value of a key that doesn’t exist? Can you guess? Let’s try it and see!

>>> participant['age']
Traceback (most recent call last):
  File "", line 1, in 
KeyError: 'age'

Look, another error! This one is a KeyError. Python is helpful and tells you that the key 'age' doesn’t exist in this dictionary.

When should you use a dictionary or a list? Well, that’s a good point to ponder. Just have a solution in mind before looking at the answer in the next line.

  • Do you just need an ordered sequence of items? Go for a list.
  • Do you need to associate values with keys, so you can look them up efficiently (by key) later on? Use a dictionary.

Dictionaries, like lists, are mutable, meaning that they can be changed after they are created. You can add new key–value pairs to a dictionary after it is created, like this:

>>> participant['favorite_language'] = 'Python'

Like lists, using the len() method on the dictionaries returns the number of key–value pairs in the dictionary. Go ahead and type in this command:

>>> len(participant)
4

I hope it makes sense up to now. :) Ready for some more fun with dictionaries? Read on for some amazing things.

You can use the pop() method to delete an item in the dictionary. Say, if you want to delete the entry corresponding to the key 'favorite_numbers', just type in the following command:

>>> participant.pop('favorite_numbers')
[7, 42, 92]
>>> participant
{'country': 'Canada', 'favorite_language': 'Python', 'name': 'Commonlounge'}

As you can see from the output, the key–value pair corresponding to the favorite_numbers key has been deleted.

As well as this, you can also change a value associated with an already-created key in the dictionary. Type this:

>>> participant['country'] = 'Germany'
>>> participant
{'country': 'Germany', 'favorite_language': 'Python', 'name': 'Commonlounge'}

As you can see, the value of the key 'country' has been altered from 'Canada' to 'Germany'. :) Exciting? Hurrah! You just learned another amazing thing.

Summary

Awesome! You know a lot about programming now. In this last part you learned about:

  • variables – names for objects that allow you to code more easily and to make your code more readable
  • lists – lists of objects stored in a particular order
  • dictionaries – objects stored as key–value pairs

Excited for the next part? :)

Based on content from https://tutorial.djangogirls.org/en/python_introduction/


© 2016-2022. All rights reserved.