Python Lists

A list is a sequence of indexed and ordered values like an array. It is mutable, means we can change the order of elements in a list. So, we should use list if the contents of the sequence may change and use tuple if the contents will not change. It contain list of any type of data objects with comma separated and enclosed within a square bracket. Each element of list has an index, starting with 0, 1 and so on. Here is the format of a list -

[expr1, expr2, ...]

The zero or more values of the list are enclosed within square brackets [...].


Example of Python list

>>> list = [10, 33, "Hello", 34]
>>> print list
[10, 33, 'Hello', 34]

Python List Operations


Python Concatenate Two Lists

Addition sign is used to concatenate two lists, like -

>>> list1 = [10, 33, 34]
>>> list2 = ["Hello", "World"]
>>> print(list1 + list2)
[10, 33, 34, 'Hello', 'World']

Output of the above code
Python List

Python Get Listed Element

We can access a list element using their index.

>>> list = [10, 33, 34]
>>> print(list[0])
10
>>> print(list[2])
34


Add element to the exiting list

The append() method is used to add single element to the list. It adds only a single element. We can use concatenate to add more than one element.

>>> newnums = [10, 33, 34]
>>> newnums.append(54)
>>> print(newnums)
[10, 33, 34, 54]


Python Insert Element

Python provides insert() method to insert new value at a given arbitrary position.

>>> items = ["Car", "Bus", "Train"]
>>> items.insert(1, "Cycle")
>>> items
['Car', 'Cycle', 'Bus', 'Train']


Python Update Element

To update any element of a list, simply reassign value using their index position.

>>> newnums = [10, 33, 34]
>>> newnums[2] = 55
>>> print(newnums)
[10, 33, 55]


Python Delete Element

There are several methods to delete an element -

pop()

This method modifies the list and simply delete the element that was removed and does not provide an index.

>>> newnums = [10, 33, 34]
>>> x = newnums.pop(1)
>>> print newnums
[10, 34]
>>> print x
33

del statement

It completely delete the element and reassign the index value.

>>> newnums = [10, 33, 34]
>>> del newnums[0]
>>> print newnums
[33, 34]

del is also used to delete multiple elements in range.

>>> newnums = [10, 33, 34]
>>> del newnums[0:1]
>>> print newnums
[33, 34]

remove()

If you want to remove the element only but not index, than use remove.

>>> newnums = [10, 33, 34]
>>> x = newnums.remove(10)
>>> print newnums
[33, 34]
>>> print x
None

List Slices

The slice operator works on the list.

>>> t = [10, 22, 12, 43, 53, 29, 43]
>>> t[1:4]
[22, 12, 43]

Sort List

Sort method is used to sort the list element from low to high.

>>> t = [10, 22, 12, 43, 53, 29, 43]
>>> t.sort();
>>> print t;
[10, 12, 22, 29, 43, 43, 53]