Append In Python

In this notebook, We will go over following...

  1. Python List Append
  2. Python Dictionary Append

Python List Append

Let us first go through properties of Python List.

  1. Python Lists need not to be of same data type
  2. A list can contain data Types such as Integers, Strings, as well as lists.
  3. Lists are mutable, which means they can be altered even after their creation.
  4. Lists in Python are indexed. That means Python Lists can have duplicate entries
In [1]:
tmp_list = [1,"one",'#',2]

Let us try appending to the above list using append() method. Note append() will add element to the end of list.

In [2]:
tmp_list.append("two")
In [3]:
tmp_list
Out[3]:
[1, 'one', '#', 2, 'two']

We can also append list inside list using append() method.

In [4]:
tmp_list.append(["this","is","list","no",2])
In [5]:
tmp_list
Out[5]:
[1, 'one', '#', 2, 'two', ['this', 'is', 'list', 'no', 2]]

Let us try now indexing. Indexes are counted from 0 in Python. To access element 2nd, we will have to use the index 1.

In [6]:
tmp_list[1]
Out[6]:
'one'

Python Dictionary Append

  1. Python dictionaries are mutable that is Dictionary values have no restrictions. They can be arbitrary objects such integers, strings, characters or even user defined objects.
  2. However Dictionary keys are immutable.

Let us declare a Python dictionary with some arbitrary content.

In [7]:
mydict = {'Name':'John','first_three_odd_nos':[1,3,5]}
In [8]:
mydict
Out[8]:
{'Name': 'John', 'first_three_odd_nos': [1, 3, 5]}

Let us append to the above dictionary a new key value pair

In [9]:
mydict['Job'] = 'Engineer'
In [10]:
mydict
Out[10]:
{'Name': 'John', 'first_three_odd_nos': [1, 3, 5], 'Job': 'Engineer'}

Note, a new key,value pair is added. From Python 3.6 onwards, the standard dict type maintains insertion order by default. But if are using older version of Python, insertion order is not maintained.

Since values in Python dictionaries are mutable, we can change the value of any key.

In [11]:
mydict['Job'] = 'Doctor'

Python dictionary update() method can be used to append.

In [12]:
mydict.update({'Alex':'Scientist'})
In [13]:
mydict
Out[13]:
{'Name': 'John',
 'first_three_odd_nos': [1, 3, 5],
 'Job': 'Doctor',
 'Alex': 'Scientist'}