Categories
Python

What Is A List In Python And How To Use Them

Lists are great for storing collection of related objects. Let’s understand dynamic, mutable and heterogenous nature of Python lists.

Introduction To List

In Python, Lists are very similar to the notion of an array in other programming languages. You can think of a list as an indexed collection of related objects where each slot is indexed from zero to upward.

Did you know ?

List is one of the most used in-built data structures in Python.

Photo by Glenn Carstens-Peters on Unsplash

Fun Facts About Lists

  • Unlike arrays, lists are dynamic, which means they can grow or shrink on demand.
  • Due to dynamic nature of lists, you don’t need to predeclare the size of list.
  • List are also heterogeneous so you don’t need to pre-declare the type of objects you are storing.
  • You can even mix & match objects of different types and store them in one list if you like.
  • Lists are mutable in nature so you can easily modify a list by adding, removing, or updating the elements of a list.

Theory is good and all but now let’s understand each concept through an example.

Creating a list

There are two ways to create a list :-

  • One way is to use the List class –>
l = list()
  • The other way would be to use square brackets –>
l = []

Using square brackets is the most used way to create a list as it is more concise.

Initializing a list

Most of us know how to initialize a list as it’s the same in all languages. And so we should directly see it’s practical implementation :-

names = ['john', 'wick', 'baba', 'yaga']
scores = [23, 45, 12, 78]

Modifying a list (Mutable)

  • Adding an element in a list –>

Python provides us with append() method to add an element at the end of the list. It’s pretty easy, let’s see how this is done :-

names = ['john', 'wick', 'baba', 'yaga']
names.append('daredevil')
print(names) # ['john', 'wick', 'baba', 'yaga', 'daredevil']
  • Removing an element from a list ( using pop() method ) –>

Using pop() method will remove an object from list that is present at the end.

names = ['john', 'wick', 'baba', 'yaga']
names.pop()
print(names) # ['john', 'wick', 'baba']
  • Removing an element from a list ( using remove() method ) –>

Using remove() method will remove an object from a list if it exists otherwise it throws an error.

names = ['john', 'wick', 'baba', 'yaga']
names.remove('john')
print(names) # ['wick', 'baba', 'yaga']


# Error if object does not exists in list
names.remove('dare')
# --------------------------------------
Traceback (most recent call last):
  File "c:/Users/hp/Desktop/NodePractice/test.py", line 2, in <module>
    names.remove('dare')
ValueError: list.remove(x): x not in list
  • Updating elements of a list –>

Now let’s see another way we can modify a list by updating the value of an existing element. You can use the index of the element in a list to directly modify the value of an element in a list.

names = ['john', 'wick', 'baba', 'yaga']
print(names[1]) # 'wick'
names[1] = 'dare'
print(names) # ['john', 'dare', 'baba', 'yaga']

Heterogenous Nature Of List

A heterogenous list is just a list containing elements with various data types.

For this purpose let’s consider an example where we initialize a heterogenous list that holds a string, int and a float type element :-

hetro = ['johh', 45, 23.6]

The Dynamic Nature Of List

They dynamic nature of list allows us as a developer to easily modify lists on the fly. In below example, we first declare an empty list. Then we add and remove items as we go along using append() and remove() method :-

empty = []
empty.append('john')
empty.append(45)
empty.append('baba')
print(empty) # ['john', 45, 'baba']
empty.remove('john')
print(empty) # [45, 'baba']

In short, while using lists, we can add and remove elements at any point of time and our list grows and shrinks accordingly.

Membership Test(in operator)

You can use the in operator to check if element exists in a list or not, let’s see how :-

l = [1, 34, 12,45,98]
if 34 in l:
   print('exists')
else:
   print('not exists')
# exists

if 20 in l:
   print('exists')
else:
   print('not exists')
# not exists

Extending list with objects.

At this point, we are already aware of the append() method to add a single element to a list. Similarly, we can add multiple objects in a list and for that we can use the extend() method.

extend() method takes a list of data as its sole argument and adds it at the end of our list.

l = [10, 15, 5]
l.extend([23, 3])
print(l)
# [10, 15, 5, 23, 3]

Insert an object into list

We know that append() and extend() methods helps us add a element at the end of our list. But what if we have a requirement where we need to add the element at a specific index in the list.

Whenever this issue arises, insert() method comes at the rescue. The insert() method takes two argument –> The index where the element is to be added and the element itself.

l = [10, 5, 23]
l.insert(0, 20)
print(l)
# [20, 10, 5, 23]

In case you would like to explore more methods of list. Please refer here !!

Summary

To conclude this article, let us see what we have covered in this article. Firstly, we got to know that lists are used to store a collection of related objects. Moreover unlike arrays, lists are dynamic in nature. Then we saw the dynamic and heterogenous nature of lists. Lastly, we saw how to modify a list and how to handle multiple various type of objects in a list.

Hope you have enjoyed this article. Good Luck, Happy Coding.

Let the author know what's in your mind !!

This site uses Akismet to reduce spam. Learn how your comment data is processed.