Append In Python
In this notebook, We will go over following...
- Python List Append
- Python Dictionary Append
Python List Append
Let us first go through properties of Python List.
- Python Lists need not to be of same data type
- A list can contain data Types such as Integers, Strings, as well as lists.
- Lists are mutable, which means they can be altered even after their creation.
- Lists in Python are indexed. That means Python Lists can have duplicate entries
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.
tmp_list.append("two")
tmp_list
We can also append list inside list using append() method.
tmp_list.append(["this","is","list","no",2])
tmp_list
Let us try now indexing. Indexes are counted from 0 in Python. To access element 2nd, we will have to use the index 1.
tmp_list[1]
Python Dictionary Append
- 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.
- However Dictionary keys are immutable.
Let us declare a Python dictionary with some arbitrary content.
mydict = {'Name':'John','first_three_odd_nos':[1,3,5]}
mydict
Let us append to the above dictionary a new key value pair
mydict['Job'] = 'Engineer'
mydict
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.
mydict['Job'] = 'Doctor'
Python dictionary update() method can be used to append.
mydict.update({'Alex':'Scientist'})
mydict