~ Lists: Adding to


Adding to a list

Making list is well and good, but we often need to change them later.

To return to the teacher/grades example: what happens when there's another test, and we need to add a new grade to the list?

There's a few ways to add onto lists in Python, depending on where we want to put the new data.

Adding to the end of a list

The append(..) command adds whatever is in parentheses onto the end of the list.

a = ['a', 'b', 'c', 'd']
a.append(42)
a --> ['a', 'b', 'c', 'd', 42]

Inserting at a specific point

If you want to insert an item at a specific place in a list, the .insert(POSITION, ITEM) command looks like this:

b = ['m', 'n', 'o', 'p', 'q', 'r']
b.insert(24, 2)
b --> ['m', 'n', 24, 'o', 'p', 'q', 'r']
b.insert(2, 20)
b --> ['m', 'n', 20, 'o', 'p', 'q', 'r', 2]

If you use a position that's longer than the list – like the 24 above – Python inserts the item at the end of the list, rather than giving you an error.

Gluing lists together

There's two ways of extending, or adding several things onto, a list. The first uses the extend([]) instruction, and the second the + operator.

Extending with +

When you add lists with a +, Python "glues" the lists together:

[4,5,6] + [1,2,3] --> [4,5,6,1,2,3] 

No matter how many lists you add, you'll always end up with one, comprehensive list at the end.

Extending with extend

x = [1, 2, 3, 4]
x.extend(['a', 'b', 'c'])
x --> [1, 2, 3, 4, 'a', 'b', 'c']

Multiplying a list

Lists can be multiplied by numbers; when you do this, Python's actually multiplying the occurences of each element, rather than multiplying the elements themselves. For example:

[1,2] * 3 --> [1,2,1,2,1,2]
[7] * 7 --> [7,7,7,7,7,7,7]
['c'] * 4 --> ['c','c', 'c','c']

Challenge

Start with the list li = [1, 2, 3, 4, 5] in the console below.

  1. Use one of the commands above to turn it into li = [1, 2, 3, 4, 5, "hi!"]
  2. Then, use a different command to turn the list into li = [1, 2, 3, 4, 5, "hi!", "hello!", "yo!"]