List Operation in Python - Part 1

In this article, we'll learn everything about Python Lists; how lists are created in Python, slicing of a list, adding or removing elements from the list and so on. The list is a versatile datatype available in Python which can be written as a list of comma-separated values (items) between square brackets. In Python's list we can store elements of different types. Following is an example of a list in Python where we are storing some strings and numbers: 

List = ['Mathematics', 'chemistry', 1997, 2000]

How to create a list ?

In Python programming, a list is created by putting different comma-separated values between square brackets [ ]. It can have any number of items and they may be of different types (integer, float, string etc.).

# empty list
my_list = []

# list of integers
my_list = [1, 2, 3]

# list with mixed datatypes
my_list = [1, "Hello World!", 3.4]

In addition, a list can have another list as an item. This is called nested list.

# nested list
my_list = ["Hello World!", [8, 4, 6], ['a']]

How to access elements of a list?

We can use the index operator [index] to access an item in a list. Indexing in Python starts from 0. So, a list having 5 elements will have index from 0 to 4. Trying to access an element other than this will give an IndexError. The index must be an integer. We can't use float or other types, this will result into TypeError. Following are example of accessing list elements by index.

my_list = ['T','U','T','U','R','S','E','L','F']

# Output: T

# Output: T

# Error! Only integer can be used for indexing
# my_list[4.0]

# Example of Nested List
n_list = ["Happy", [2,0,1,5]]

# Example of Nested indexing, it is handled like a 2D array in other programming language
# Output: a

# Output: 5

Python also allows negative indexing:

Python also allows negative indexing for a List. The index of -1 refers to the last item which is nth record in the list, -2 to the second last item and so on.

my_list = [ 'T','U','T','U','R','S','E','L','F' ]

# Output: F

# Output: R

Slice of a List:

The values stored in a list can be accessed using the slice operator ([ ] and [:]) with indexes starting at 0 in the beginning of the list and working their way to end -1. The plus (+) sign is the list concatenation operator, and the asterisk (*) is the repetition operator. Following are the example of slice operator in List:

my_list = ['T','U','T','U','R','S','E','L','F']

# elements 3rd to 5th

# elements beginning to 4th

# elements 6th to end

# elements beginning to end

Read the article to find more about slice.

Add and Modify values in a List :

  • The append() method is used to append or add an element in List. The append() method is used to add an element to the last of the List.
# Adds List Element as value of List.

List = ['Mathematics', 'chemistry', 1997, 2000]



['Mathematics', 'chemistry', 1997, 2000, 20544]

  • The insert() method is used to add an element in a specified position in the List. The syntax of the insert method is as following:

list.insert(position, element)

The position should be in the range of the list, as in this case the range is between 0 and 4, otherwise it would throw IndexError.

  • The extend() method can be used to concatenate two lists. The following code  Adds contents to List2 to the end of List1.

List1 = [1, 2, 3]
List2 = [2, 3, 4, 5]

# Add contents of List2 to the end of List1

#Add List1 to List2 now
  • Built-in functions like all()any()enumerate()len()max()min()list()sorted() etc. are commonly used with list to perform different tasks.

    Built-in Functions with List

    Function Description
      all()   Return True if all elements of the list are true (or if the list is empty).
      any()   Return True if any element of the list is true. If the list is empty, return False.
      enumerate()     Return an enumerate object. It contains the index and value of all the items of list as a tuple.
      len()   Return the length (the number of items) in the list.
      list()   Convert an iterable (tuple, string, set, dictionary) to a list.
      max()   Return the largest item in the list.
      min()   Return the smallest item in the list
      sorted()   Return a new sorted list (does not sort the list itself).
      sum()   Return the sum of all elements in the list.

Python 12


Explore Tutu'rself