A Python List

Take a look at this example:

age = 108
name = 'Joe King'
print ('my name is ' + name + '. I am', age, 'years old') 

Notice that when we use the age variable, we don’t use the ‘+’ symbol? Do you want to guess why?

This is because age is an integer, not a string. These are different data types. Concatenation only works on strings. If we tried to use concatenation (the plus symbol), Python would give us this error:

>>> print ('my name is ' + name + '. I am' + age + 'years old')
Traceback (most recent call last):
File "", line 1, in
TypeError: can only concatenate str (not "int") to str

This is what we would expect. Python has called this a Type Error (that is, an error caused by using the wrong data type). It even tells us that we can’t concatenate integers, only strings.

So what are we doing instead? By using commas, we’re passing a list to the print function. This contains three items:

  1. A String (‘my name is Joe King. I am’)
  2. An integer (the age variable, containing the value 108)
  3. A String (‘years old’)

Python will look at this and think “I have been given a list, and I need to print each of these items”.

It will happily print the integer, as we’re not mixing it with a string. It is a completely separate list item.

A list is a data type. It contains items, which can be of different data types.