Python List

This blog post is about appending data elements to list in Python.

Suppose we have a simple list “x”, we will look at different ways to append elements to this list.

x = [1, 2, 3]

The “append” method appends only a single element

>>> x
[1, 2, 3]
>>> x.append(4)
>>> x
[1, 2, 3, 4]
>>>

>> x.append(5, 6, 7)
Traceback (most recent call last):
File "", line 1, in
TypeError: append() takes exactly one argument (3 given)
>>>

How do you append multiple elements to list?

>>> x[len(x):] = [5, 6, 7]
>>> x
[1, 2, 3, 4, 5, 6, 7]
>>>

Another way to append multiple elements is create a new list and use “+” operator

>>> y = [8, 9, 10]
>>> x = x + y
>>> x
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>>

The other way which I learned today is to use “extend” method

>>> z = [ 11, 12, 13]
>>> x.extend(z)
>>> x
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
>>>

Incase you want to add new list elements between two existing elements, then use “insert” method.

>>> x.insert(5, "Hi")
>>> x
[1, 2, 3, 4, 5, 'Hi', 6, 7, 8, 9, 10, 11, 12, 13]
>>>
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s