An Introduction To Python Lists

Introduction

 
A list is an in-built data structure in Python programming language. It is a collection of elements that can be accessed by their indexes.
 
Following are some of the important points about a list in Python,
  • Lists are mutable objects (changeable objects) which simply means once you create a list you can modify it anytime. 
  • Lists elements are accessed by an index, a list's index always starts from 0. Say we have a list with “n” elements, then the last element will have an index of “n-1”.
  • A list can contain any number of elements and that elements can be of any data type. So we can say lists are the collection of heterogeneous data types.
  • A list can contain duplicate elements.

How to declare a list?

  1. In Python, we can create a list by simply placing elements inside square brackets [ ], separated by a comma.



    The output of the above code snippet is shown below:



    Here we can see the list contains string, integer, and boolean type elements.
  1. We can also create a list object by using list() constructor, the syntax for a list() is list([iterable]) here iterable is an optional parameter which could be a string or tuple, or any other iterable object.



    The output of the above code snippet is:



    Here we can see if we don't pass any argument to list() constructor it will simply return an empty list.

    Now let's pass an argument to list() and see what happens:



    The output of the above code snippet is:

Here, we can see when we pass a string as an argument to list() constructor, it returns a list.
 

How to access list elements?

 
We can access list elements by using their forward & backward index numbers.
  • Forward indexes start from 0 and go to n-1.
  • Backward indexes start from -1 and go to -n.
Let's access list elements with an example as well:
 
 
The output of the above code snippet is:
 
 
Here in the output, we can see that the list elements can be accessed by their forward or backward index numbers.
 

List Methods

 
A list data structure mainly have the following methods:
  1. Append
  2. Extend
  3. Clear
  4. Copy
  5. Count
  6. Index
  7. Insert
  8. Pop
  9. Remove
  10. Reverse
  11. Sort
We will discuss these methods in the next article.
 

Summary

 
In this article, we discussed the basic concepts of a list. This is my first article and I hope this will help readers to understand the basics of a list. In the next article, we will discuss the methods of lists.
 
Please share your feedback and queries related to this article. Thanks for reading!


Recommended Free Ebook
Similar Articles