List in Python

Table of contents
Reading Time: 4 minutes

Python_logo_and_wordmark.svg

In this blog, we are going to discuss the list data structure of python.

The list is a collection which is:
• Ordered : [1,2] is not equal to [2,1]
• Allows duplicate members: [1, 1] is allowed.
• Mutable: allows modification of elements of the list after its creation.
• Dynamic: allows addition, modification or deletion of elements.

The differentiating feature between arrays from other languages and list is that lists need not be homogeneous always which makes it a most powerful tool in Python. Lists can be nested to arbitrary depth.

DECLARE LIST

Lists can be declared using square braces or list constructor.

>>> emptylist = []
>>> emptylist
[]

>>> type(emptylist)

>>> emptylist = list()
>>> emptylist
[]
The syntax of list() constructor is:
list([iterable])
>>> list(1)
Traceback (most recent call last):
File “”, line 1, in
TypeError: ‘int’ object is not iterable

>>> list(‘a’)
[‘a’]

>>> list({1: ‘a’}) # Lists take dictionary keys
[1]

ACCESS ELEMENTS OF LIST

>>> list = [1, 2, 3]
>>> list[0]
1

>>> list[-1] # using negative indexing
3

>>> list[-3]
1

>>> list[-7]
Traceback (most recent call last):
File “”, line 1, in
IndexError: list index out of range

ADD ELEMENTS TO LIST

>>> list = [1, 2, 3, 4]
>>> list.insert(0,10)
>>> list
[10, 1, 2, 3, 4]

>>> list = [1, 2, 3, 4]
>>> list.append(5)
>>> list
[1, 2, 3, 4, 5]

>>> list.extend(8)
Traceback (most recent call last):
File “”, line 1, in
TypeError: ‘int’ object is not iterable

>>> list.extend([8,10])
>>> list
[1, 2, 3, 4, 5, 8, 10]

append() adds a single element to list while extend() adds multiple elements to a list.

MODIFYING ELEMENTS OF LIST

>>> list = [1, 2, 3, 4]
>>> list[0] = 7
>>> list
[7, 2, 3, 4]

>>> list[1:3]=[6, 8]
>>> list
[7, 6, 8, 4]

ITERATE ITEMS OF LIST

>>> list = [1, 2, 3, 4]
>>> for item in list:
… print(item)

1
2
3
4

OPERATORS ON LIST

>>> list = [1, 2, 3, 4]
>>> listOne = [4, 5]
>>> list + listOne #list concatenation
[1, 2, 3, 4, 4, 5]
>>> listOne * 3
[4, 5, 4, 5, 4, 5]

>>> list = [1, 2, 3, 4, 5, 5]
>>> list += [9, 10]
>>> list
[1, 2, 3, 4, 5, 5, 9, 10]

DELETING ELEMENTS OF LIST

>> list = [1, 2, 3, 4]
>>> del list[0]
>>> list
Traceback (most recent call last):
File “<stdin>”, line 1, in <module>
NameError: name ‘list’ is not defined
>>> list = [1, 2, 3, 4]
>>> del list[1:3]
>>> list
[1, 4]

>>> list = [1, 2, 3, 4, 5]
>>> list[1:3] = []
>>> list
[1, 4, 5]

>>> list = [1, 2, 3, 4, 5, 5]
>>> list.remove(5)
>>> list
[1, 2, 3, 4, 5]

>> list.remove(5)
>>> list
[1, 2, 3, 4]

FUNCTIONS ON LIST

>>> list = [1, 2, 3, 4, 5, 5]
>>> list.index(3)
2

>>> list.count(5)
2

>>> max(list)
5

> min(list)
1

>>> list.reverse()
>>> list
[5, 5, 4, 3, 2, 1]

CHECK EXISTENCE OF ITEM IN LIST

>>> list = [1, 2, 3, 4, 5, 5]
>>> 1 in list
True
>>> 7 in list
False

DELETE the WHOLE LIST

>>> list = [1, 2, 3, 4, 5, 5]
>>> del list
>>> list

>>> list = [1, 2, 3, 4, 5, 5]
>>> list.clear()
>>> list
[]

list.clear() is equivalent to del list[:].

LIST COMPREHENSION

>>> listOne = [ item * 2 for item in range(10) if item % 2 == 0 ]
>>> listOne
[0, 4, 8, 12, 16]

LIST AS STACK (LIFO)

>>> list = [1, 2, 3, 4, 5]
>>> list.append(10)
>>> list
[1, 2, 3, 4, 5, 10]

>>> list.pop()
10

>>> list
[1, 2, 3, 4, 5]

ACCESSING ITEMS OF NESTED LIST

>>> old_list
[[1, 30, 3], [4, 5, 6], [7, 8, 9], [4, 4, 4], [4, 4, 4]]

>>> old_list[2][2]
9

It is also possible to use a list as a queue, however, lists are not effective for this purpose. While appends and pops from the end of the list are fast, doing inserts or pops from the beginning of a list is slow (because all of the other elements have to be shifted by one).

LIST SORT VS SORTED

sorted() returns a new sorted list, leaving the original list unaffected. list.sort() sorts the list in-place, mutating the list indices, and returns None (like all in-place operations).

Use list.sort() when you want to mutate the list, sorted() when you want a new sorted object back. Use sorted() when you want to sort something that is an iterable, not a list yet.
For lists, list.sort() is faster than sorted() because it doesn’t have to create a copy. For any other iterable, you have no choice.

No, you cannot retrieve the original positions. Once you called list.sort() the original order is gone.

>>> list = [5, 2, 4, 1, 7]
>>> list.sort()
>>> list
[1, 2, 4, 5, 7]

>>> list = [5, 2, 4, 1, 7]
>>> sorted(list)
[1, 2, 4, 5, 7]
>>> list
[5, 2, 4, 1, 7]

LIST COPY

>>> list = [5, 2, 4, 1, 7]
>>> listOne = list
>>> listOne
[5, 2, 4, 1, 7]

>>> list[0] = 10
>>> list
[10, 2, 4, 1, 7]

>>> listOne
[10, 2, 4, 1, 7]

The assignment just copies the reference to the list, not the actual list, so both list and listOne refer to the same list after the assignment.

>>> old_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> new_list = old_list.copy()
>>> old_list.append([4, 4, 4])
>>> old_list
[[1, 2, 3], [4, 5, 6], [7, 8, 9], [4, 4, 4]]
>>> new_list
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

A deep copy is a process in which the copying process occurs recursively.

>>> import copy
>>> old_list
[[1, 30, 3], [4, 5, 6], [7, 8, 9], [4, 4, 4]]

>>> new_list = copy.deepcopy(old_list)
>>> old_list.append([4, 4, 4])
>>> new_list
[[1, 30, 3], [4, 5, 6], [7, 8, 9], [4, 4, 4]]

Thanks for reading!!


Knoldus-blog-footer-image

Written by 

Jyoti Sachdeva is a software consultant with more than 6 months of experience. She likes to keep up with the trending technologies. She is familiar with languages such as C,C++,Java,Scala and is currentky working on akka,akka http and scala. Her hobbies include watching tv series and movies, reading novels and dancing.