Lists are what you’d think, a list. Lists in Python store multiple values in a single variable (a.k.a. Python object). The values can be mix types, i.e. a single list can contain both numbers or character type values.

To create an empty list, you use the “[]” brackets.

lst = []

 

Assigning values to a list

Let’s create a list and assign it some values, both strings and numeric values.

lst = ['Apples', 'Cherries', 'Blueberries', 2017]

 

Indexing and Slicing

Lists can be indexed and sliced just list strings, dictionaries, data frames, and series. Remember that in Python the index starts at 0.

lst[0]
Apples

 

lst[3]
2017

 

lst[:2]
[‘Apples’, ‘Cherries’]

 

Adding and Changing Values

Lists are mutable. This means we can change the values within it.

lst[1] = 'Honey'

lst
[‘Apples’, ‘Honey’, ‘Blueberries’, 2017]

 

Notice how “Honey” replaced “Cherries”.

It is possible to add values to an existing list. When you add a value to an existing list, Python adds the value to the end of the list. To do this, we use the .append() method.

lst.append('2015')

lst
[‘Apples’, ‘Honey’, ‘Blueberries’, 2017, ‘2015’]

 

How long is a list?

We can find out the length of lists with the .len() method.

len(lst)
5

 

Is something in a list?

You can ask Python if something is in a list. If it is in the list, then Python will return a Boolean value of “True”; otherwise Python will return a Boolean value of “False”.

'Apples' in lst
True

 

'Chocolate' in lst
False

 

Concatenation

Concatenation means to combine, join, or add. When you concatenate 2 lists, you are adding the list items together.

lst2 = ['Chocolate', 28]

lst3 = lst + lst2

lst3
[‘Apples’, ‘Honey’, ‘Blueberries’, 2017, ‘2015’, ‘Chocolate’, 28]

 

Since we assigned the concatenated lists to a new list variable, we retained the original lists with their respective values

lst
[‘Apples’, ‘Honey’, ‘Blueberries’, 2017, ‘2015’]

 

lst2
[‘Chocolate’, 28]