Python language basics 41: 4 ways to insert new elements into a collection
August 23, 2015 Leave a comment
Introduction
In the previous post we looked at negative indexes for collections. We saw how they could be used to access elements from the tail of the list. An index of -1 will help you get to the last element of a collection regardless of its size.
In this post we’ll look at 4 ways to insert elements into a collection.
Element insertion
Consider the following cities collection:
cities = ["Stockholm", "Budapest", "Berlin", "Paris", "Birmingham", "Zürich"]
The insert function
If you want to insert a new element just after “Berlin”, i.e. at position 4 – or 3 as indexes are 0-based, then you can use the insert function. This function accepts an index where to put the new item and an object to be inserted:
cities.insert(3, "Oslo")
Here’s the revised list:
[‘Stockholm’, ‘Budapest’, ‘Berlin’, ‘Oslo’, ‘Paris’, ‘Birmingham’, ‘Zürich’]
The append function
If you want to add an item to the end of the list then use the append method:
cities.append("London")
…which will extend the cities list accordingly:
[‘Stockholm’, ‘Budapest’, ‘Berlin’, ‘Paris’, ‘Birmingham’, ‘Zürich’, ‘London’]
The + and += operators
You can insert multiple elements to the end of list using the + and += operators:
cities = ["Stockholm", "Budapest", "Berlin", "Paris", "Birmingham", "Zürich"] more_cities = ["Barcelona", "Helsinki", "Copenhagen", "Moscow"] joined_cities = cities + more_cities
…where joined_cities will include all city names as expected:
[‘Stockholm’, ‘Budapest’, ‘Berlin’, ‘Paris’, ‘Birmingham’, ‘Zürich’, ‘Barcelona’, ‘Helsinki’, ‘Copenhagen’, ‘Moscow’]
If you want to append the “more_cities” collection to “cities” instead of building a new collection then you can use the += operator:
cities = ["Stockholm", "Budapest", "Berlin", "Paris", "Birmingham", "Zürich"] more_cities = ["Barcelona", "Helsinki", "Copenhagen", "Moscow"] cities += more_cities
‘cities’ will become…
[‘Stockholm’, ‘Budapest’, ‘Berlin’, ‘Paris’, ‘Birmingham’, ‘Zürich’, ‘Barcelona’, ‘Helsinki’, ‘Copenhagen’, ‘Moscow’]
The extend function
The extend function has the same effect as the += operator:
cities = ["Stockholm", "Budapest", "Berlin", "Paris", "Birmingham", "Zürich"] more_cities = ["Barcelona", "Helsinki", "Copenhagen", "Moscow"] cities.extend(more_cities)
Again, cities will include all city names:
[‘Stockholm’, ‘Budapest’, ‘Berlin’, ‘Paris’, ‘Birmingham’, ‘Zürich’, ‘Barcelona’, ‘Helsinki’, ‘Copenhagen’, ‘Moscow’]
In the next post we’ll look at a couple of ways to remove an element from a list.
Read all Python-related posts on this blog here.