Python List Methods: Adding Items

Check out this refresher on ways to add items to python lists

“Share your knowledge. It is a way to achieve immortality.” ― Dalai Lama XIV

1. Introduction

Python offers the list data type which is similar to an array in C/C++ or Javascript or a List in Java. Of course, there are differences between the list in python and these languages. Sigh, wouldn’t it have been nice if all the common languages offered such data types with the same methods – same name, parameters, everything? Then you could have concentrated on mastering one and you would have it all. At the very least, this could have been done for common programming entities such as strings, list/array, characters, integer and float numbers, booleans, etc.

Let us stop dreaming and get on with reviewing the list data type in python.

2. Creating a List

A list is an ordered collection of items. A list is represented in python code by enclosing the items inside a pair of brackets. For example:

a = ['cat', 'dog', 'snake', 'cow']

All items in the list need not be of the same type.

a = ['apples', 'bread', 24, 3.3, True]

How do you create an empty list? Use empty brackets.

a = []
print len(a)
# prints
0

Here is how you can nest lists within one another.

a = ['cat', 'dog', [1, 2, 3]]
print a
# prints
['cat', 'dog', [1, 2, 3]]

3. Adding Items to Lists

The following methods on a list object are used to add items to the list – append(), extend(), insert() and the addition operator (+).

3.1. append()

Use the append() method to append a single item to the end of the list.

a = ['cat', 'dog', 'snake', 4]
print a
a.append('joe')
print a
# prints
['cat', 'dog', 'snake', 4]
['cat', 'dog', 'snake', 4, 'joe']

When you pass another list to the append() method, it is added as a sublist.

a = ['cat', 'dog', 'snake', 4]
print '1.', a
a.append(['scorpion', 'spider'])
print '2.', a
print '3.', a[len(a)-1]
# prints
1. ['cat', 'dog', 'snake', 4]
2. ['cat', 'dog', 'snake', 4, 'joe', ['scorpion', 'spider']]
3. ['scorpion', 'spider']

3.2. extend()

The method extend() is another way to add items to the end of the list. It expects an list (or an iterable) as an argument and adds all the items at the end in the same order.

a = ['cat', 'dog', 'snake', 4]
print '1.', a
a.extend(['scorpion', 'spider'])
print '2.', a
# prints
1. ['cat', 'dog', 'snake', 4]
2. ['cat', 'dog', 'snake', 4, 'scorpion', 'spider']

In other words, the list argument is “unpacked” into the original list object.

What happens when you pass extend() a single object, such as a string? The string is again “unpacked” and added to the end.

a.extend('joe')
print '3.', a
# prints
3. ['cat', 'dog', 'snake', 4, 'scorpion', 'spider', 'j', 'o', 'e']

No wonder then, when you add a non-iterable object, you are informed with an exception in your face.

try: a.extend(3)
except Exception as x:
    print '5.', x
print '4.', a
# prints
5. 'int' object is not iterable

3.3. Difference between append() and extend()

The method append() expects a single argument, and adds it as-is to the end of the list.

The extend() method, on the other hand, expects an iterable (e.g. a list) and adds all the items in the iterable as single items.

3.4. insert()

While append() and extend() add items to the end of the list, you can use insert(i, x) to add an item at a position specified by the first argument. The position index starts from 0 for the first element.

a = ['cat', 'dog', 'snake', 4]
print '1.', a
a.insert(2, 'joe')
print '2.', a
# prints
1. ['cat', 'dog', 'snake', 4]
2. ['cat', 'dog', 'joe', 'snake', 4]

You can specify a negative index to refer to the position from the end. -1 refers to the last item and the item is inserted before it.

a.insert(-2, 8)
print '3.', a
# prints
3. ['cat', 'dog', 'joe', 8, 'snake', 4]

Like append(), specifying a list or iterable as the item to be added results in a sublist being added at the specified position.

a.insert(1, ['scorpion', 'spider'])
print '4.', a
# prints
4. ['cat', ['scorpion', 'spider'], 'dog', 'joe', 8, 'snake', 4]

3.5. Operator +

Using the addition operator (+) with two or more lists results in a new list being created with the items in argument lists.

a = ['cat', 'dog', 'snake', 4]
print '1.', a
print '2.', a + ['joe']
# prints
1. ['cat', 'dog', 'snake', 4]
2. ['cat', 'dog', 'snake', 4, 'joe']

Since this operation results in the creation of a new list, it is likely more expensive than using the other methods which modify the list in place.

Note that the argument lists remain unchanged with this operation.

print '3.', a
# prints
3. ['cat', 'dog', 'snake', 4]

Attempting to add a single item to a list results in an error.

try: print a + 'joe'
except Exception as x:
    print '4.', x
# prints
4. can only concatenate list (not "str") to list

Conclusion

We have reviewed various methods of adding items to a list. We have append() which adds a single item, extend() which merges items from an iterable, insert() which can add items at a specified location and finally the add operator which creates a new list from the argument lists.

Leave a Reply

Your email address will not be published. Required fields are marked *