paint-brush
Lists in Python: Mutability, Utility, and Accessibilityby@Venky.Achintalwar
966 reads
966 reads

Lists in Python: Mutability, Utility, and Accessibility

by Venkatesh AchintalwarFebruary 18th, 2020
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

A list is a sequence in python. The dictionary meaning of list is ‘a number of connected items or names written or printed consecutively’ Python list provides the same functionality where you can group items with the flexibility of random access to each element. List is a global variable so when you declare a list and pass it to a function as an argument rather than copying and passing it to the function, python passes a reference to the list. The list has so many built-in functions that we are not going to cover all of those.

Company Mentioned

Mention Thumbnail
featured image - Lists in Python: Mutability, Utility, and Accessibility
Venkatesh Achintalwar HackerNoon profile picture

A list is a sequence in python. The dictionary meaning of list is “a number of connected items or names written or printed consecutively”. There is no much difference in its dictionary meaning and its uses in Python while writing a program.

We frequently use lists, whether it's a day to day life like making a list of groceries to buy or it's in a program like creating a list of prime numbers. We make lists whenever we want to group certain items with respect to certain criteria.

Python list provides the same functionality where you can group items with the flexibility of random access to each element, modification of each element, addition or removal of an element from it.

So, let's start with creating a list.

list1 = [1,2,3,4,5]
>>> list1
[1, 2, 3, 4, 5]
>>> type(list1)
<type 'list'>
type() is a function in python which returns the object type of a variable.

Creating a list is very simple in python. You can do it in 2 ways. First one is enclosing elements in square brackets which we have seen in the above example. Other is using the list() function.

>>> list1 = list([1,2,3,4,5])
>>> list1
[1, 2, 3, 4, 5]
>>> type(list1)
<type 'list'>

One interesting thing about lists is they store references to objects or elements in it. So, while re-assigning list to another variable, python only changes the reference rather than creating new list object.

# id() function returns the object id.
>>> id(list1)
4426491160
>>> list2 = list1
>>> id(list2)
4426491160

We can see that both variables represent the same object. This really speeds up the program execution. A list is a global variable means when you declare a list and pass it to a function as an argument rather than copying and passing it to the function, python passes a reference to the list.

The above concept is called pass-by-reference behavior. If you know what is pass-by-value and pass-by-reference then skip to the next point or if you want to know more about it read the below article.

https://robertheaton.com/2014/02/09/pythons-pass-by-object-reference-as-explained-by-philip-k-dick/

Accessing elements

Python assigns an index to each of the list elements starting from 0. So, if you want to access a particular element in the list you can access it by its index. But for that, you should know the index of the element. Even if you don’t know it, don’t worry there is one solution for that. But let’s try accessing the elements by their index for now.

>>> list1
[1, 2, 3, 4, 5]
>>> print(list1[0])
1
>>> print(list1[2])
3
>>> print(list1[1])
2

The list will throw IndexError if you pass an index which is not associated with the list or there is no element at that index.

>>> list1
[1, 2, 3, 4, 5]
>>> print(list1[9])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
>>>

There are situations where you know what element you want to access but don’t know the index of it. In such situations, you can search that element in the respective list and the search (index function in case of lists) function will return the index of that element.

>>> list1
[1, 2, 3, 4, 5]
>>> list1.index(2)
1 // index of 2
Mutable behaviour of List.

List datatype comes under the category of Mutable data structures. Mutable means you can make any changes in the data structure even after its definition. So, what changes you can do with the list? You can update an element, add a new element and remove an element.

Let us see it.

Updating list elements

>>> list1
[1, 2, 3, 4, 5]
>>> list1[0] = 2
>>> list1
[2, 2, 3, 4, 5]

Removing list element

>>> list1
[2, 2, 3, 4, 5]
>>> list1.remove(5) #remove element 5
>>> list1
[2, 2, 3, 4]

Updating and removing elements is easy and straightforward. Now, when it comes to adding an element to list, there are so many ways to do it. All it depends on where you want to add an element. One of it is using insert() function.

Inserting an element

list.insert(index, value) takes 2 arguments. First one is where you want to add element and second is the element or value itself

>>> list1
[2, 2, 3, 4]
>>> list1.insert(4,89)
>>> list1
[2, 2, 3, 4, 89] #inserting 89 at 4th index.

What if you provide an index which is very much greater than the list size? Well, in that case, the list will add the element to its last index.

>>> list1
[2, 2, 3, 4, 89]
>>> list1.insert(100000,100)
>>> list1
[2, 2, 3, 4, 89, 100]

Apart from the insert, you can use append() to add an element to the end of the list.

>>> list1 = [2, 2, 3, 4, 89, 100]
>>> list1.append(67)
>>> list1
[2, 2, 3, 4, 89, 100, 67]

We have seen basic CRUD operation with a list. The list has so many built-in functions. We are not going to cover all of those. But if you want to know more, then go to the following link.

https://docs.python.org/3/tutorial/datastructures.html

List of immutable data structures

Can we have a list of tuples? A Tuple is an immutable object and a list is a mutable object. So, if we declare a list of tuples then would it become mutable? Let’s check that out.

>>> list1.insert(6,("element1","element2"))
>>> list1
[2, 2, 3, 4, 89, 100, ('element1', 'element2')]
>>> type(list1)
<type 'list'>
>>> type(list1[6])
<type 'tuple'>
>>> list1[6][0]=3
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment

So, even if an immutable object is stored in a list, python does not alter the properties of the objects.

A list can have any datatype as its member whether it can be a dictionary, a tuple, a string or another list. This is one of the reasons why a list is so frequently used by programmers.

There is lot more about lists to learn. You’ll learn that once you start working with lists. But fundamental understanding is always necessary to learn advanced usage. I have covered the fundamentals here. If you have understood these CRUD operations you are ready to learn advance usage of a list.

So, go and explore more. I would suggest you to learn list comprehension as well. That will help you a lot while using loops with lists. That’s it for today. Keep reading. Bye...