Home » Python Basics » Python List datastructure

Python List datastructure

python list header image by aipython

Python list is the most commonly used data type. Reasons for its popularity are a list is mutable, simple to create, manipulate and handle. The list is also one of the simplest Datastructure to work with. The list can be analogous to an array in other programming languages (but not completely). There is no concept of an array in python however, there is a certain similarity between array and list as well as certain differences. The main difference between array and list is that array can store data of the same type whereas list can store data of any type (any data type).

In this article, we are going to cover topics such as basic of List, list creation in python, adding or updating values as well as various methods associated with it. As you are aware of the fact that we have a youTube channel of aipython where we are posting the video about python. The video on this topic is available at our youtube channel and the video that corresponds to list is already embedded with this blog and you can also watch the video directly on this page. Navigate to Video 1 and Video 2.


Table of contents

  1. Introduction to Python List
  2. The need for List
  3. Creating a Python list
  4. List comprehension in Python
  5. Sorting List
  6. Sequence unpacking method
  7. Membership function associated with a list in Python
  8. Commonly used Python list methods
  9. 2 Dimensional or Nested List

Introduction to Python List

Python list is a collection of data of any datatypes consolidated under one name. In a simple word list is an arrangement name to store the data of multiple datatypes. There is a certain format to store data using a list, as well as there, are defined rules to write a variable name in Python.

In a real-world scenario, one can consider racks in grocery store/supermarket as an example of List, as it stores a diversity of products like Milk, bread, sugar, Oil, vegetables etc..

python list real-world grocery store example
Real-world python list example (A grocery store)

Apart from storing data of diverse data types, sometimes list contains data of the same datatype. In such cases, based on data type, we can mention the list as Integer List, Float List, Boolean list and Complex list (We are using these names just for understanding purpose).

int_list = [ 1, 2, 3, 4, 5, 6 ]
float_list = [2.1, 3.45, 6.23, 1.91 ]
bool_list = [ 0, 1 ] # although this could be an integer list as well
com_list = [2+3j, 6-3j, 9+4j ]

The need for List

The list is essential in Python and they are used predominantly. There are many acumens for list usage which are mentioned below:

  • Programmer need ordered collection of data in the language
  • Each element in the list hold a unique index (position/location)
  • Elements can be managed (removed/updated/added) easily
  • Loops/sequence could be used to iterate over the entire list
  • Elements could be arranged or sorted

Creating a Python list

Creating a list is very simple. Image shown below is a typical visualization of the list with elements, index and element value.

python list details
Example of Python list

Method to create a List in Python

We can create an empty list (list without any element) in python. This means an instance of a list is created but there is no element in it.

my_list = [ ]

Write a variable name followed by equal ( = ) sign and then write elements separated by a comma inside a square bracket.

my_list = [ 2, 4, 6, 7, 9, 10, 100, 111 ]
print (my_list) 
[ 2, 4, 6, 7, 9, 10, 100, 111 ] 

List comprehension in Python

Accessing elements of the list

As we know now that List elements have a unique index (that is why list are known as an ordered collection). Taking an example and accessing the element by using the positive index (or simply index) method in Python.

my_list = [ 2, 4, 6, 7, 9, 10, 100, 1 1 1 ]
my_list [ 0 ] # to access 0th element 
2 

my_list [ 7 ] #to access 7th element
1 1 1  

Positive and negative index in the list

Apart from the normal indexing method (positive index), python list also facilitates the use of negative indexing. A negative index is applied in the same way as positives are.

List elements can be accessed by positive as well as negative index method, Image below shows how positive and the negative index associated with List.

Positive and negative index in python list
The Positive and negative index in python list

To get the last element of the list, we can use negative indexing method.

my_list = [ 2, 4, 6, 7, 9, 10, 100, 1 1 1 ] 

my_list [ – 1 ]
1 1 1 
my_list [ - 2 ] # to see 2nd last element of the list 
100 

Please note that if you go beyond the index limit of python list then you will get an error message from python interpreter as “IndexError:  list index out of range“. Whenever you encounter this issue try fixing code so that it fits into the list index boundary.


Slicing List elements with the index method

Slicing, in general, means getting a part of anything. List slicing means getting a portion of the list such as the first four elements of the list or last three elements of the list. We can also use the index method to slice elements between any two indexes etc. Always remember, in python, the list index starts from zero (0).

Syntax: list_name [start index : stop index ]

my_list = [ 2, 4, 6, 7, 9, 10, 100, 111 ] 

# to get first 4 elements from a list
my_list [ : 4 ] # generally we ignore to write zero if it is starting index 
2, 4, 6, 7
 
my_list [0:4] # This is another way
2, 4, 6, 7 

Python List Video Part-1

In both these above-mentioned example, Python will return element starting from start index (0 in this case) till last index (4 in this case) but not including last index value. You would have observed that element present at index 4 is not part of the result.

#To get all the value starting from index 5 to last index
my_list [ 5: ]
10, 100, 111

Now we will see how to get a portion of the list using the index method and further we will see how to get values from a specific index till the end index.

# To get all the value from index 2 to 4 but excluding 4th index
my_list [ 2:4 ] 
6, 7 

Until now, we know that List element can be accessed by index number similarly we can also find the index of an element with an element value. Don’t confuse 🙂 just read through once more

We can find the index of any element in the list by using the index method.

my_list.index (6)
2

Till now we have seen how an element or group of elements from a list can be fetched using index value. Find various list comprehension methods in python


Adding element (List Append & List Insert method)

To add an element at the end of a list we can use the append method in Python. Python list Append method takes only one argument at a time which means we can add only one element at a time. However, we can add more than one element to a python list by passing a list itself as an argument.

my_list = [ 2, 4, 6, 7, 9, 10, 100, 111 ]

my_list.append (88) 
2, 4, 6, 7, 9, 10, 100, 111, 88

my_list.append ([200, 300]) 
2, 4, 6, 7, 9, 10, 100, 111, 88, 200, 300

With the append method, we can add an element at the end of the list but there is another method to add the element at any location. Using the insert method we can add an element at any specific index location

my_list.insert (2, 55)
2, 4, 55, 6, 7, 9, 10, 100, 111, 88, 200, 300 

Removing element (List Pop & List Remove method)

To remove an element from a list we have two predominant methods which are pop and remove. To remove one element from the end of a list we use pop method while to remove a specific element by its value we use remove method. We can also pass an argument to pop method to remove an element by its index. Taking my_list value to demonstrate the case.

my_list = [ 2, 4, 55, 6, 7, 9, 10, 100, 111, 88, 200, 300 ]

my_list.pop ()
300  

# to remove a specific element from its 1st occurrence
my_list.remove(55) # does not return anything but the element will be removed 

# to remove an element from a particular index of a list
my_list.pop (1)
4

Replacing an element of a list

To replace an existing element with a new element at a particular index we use the indexing method in Python.

my_list = [2, 10, 4, 5, 9] 

# This will update the element at index 0 with a new value of 6
my_list [ 0 ] = 6

my_list
[ 6, 10, 4, 5, 9 ]

Similarly, to replace the last element of the list with some other value we will use the following code.

my_list [-1 ] = “aipython”

my_list
 [ 6, 10, 4, 5, “aipython” ] 

Note that we can replace an existing element with the same or another data type.


Extending a list in Python

Extending a list means adding one or more elements to the list so that the size of the list increases. We will use the extend method to add more elements into the python list. Python extend method accepts a list as the only argument.

We are passing even single element in the list, if you try passing 20 without the square bracket it will throw an error.

my_list = [2, 10, 4, 5, 9] 
my_list.extend ([20])

my_list
 [2, 10, 4, 5, 9, 20] 

We can also pass multiple elements as a list to extend method, like below

my_list.extend ([30, 40, 50])

my_list 
[2, 10, 4, 5, 9, 20, 30, 40, 50 ] 

We can also use ( * ) to extend the list, as shown here

my_list = [2, 10, 4, 5, 9]

my_list * 2 # this will duplicate the contents 
[2, 10, 4, 5, 9, 2, 10, 4, 5, 9 ] 

We can also use ( + ) to extend the list, as shown here

my_list = [2, 10, 4, 5, 9]

my_list + my_list   # this will duplicate the contents
[2, 10, 4, 5, 9, 2, 10, 4, 5, 9 ]  

Sorting List in Python

Sorting means arranging elements of the list in ascending or descending order. Sort function works when the datatype of the list is numeric.

Sorting in Ascending & Descending order

To sort elements in ascending order, we can write in two ways as mentioned below

my_list = [ 2, 4, 8, 0, 3, 7 ] 
my_list.sort()
[ 0, 2, 3, 4, 7, 8 ] 

my_list.sort (reverse = False)  # This will also gives the same result
[ 0, 2, 3, 4, 7, 8 ]   

To sort list elements in descending order, we write sort method with reverse equating to True

my_list.sort (reverse = True)
p[ 8, 7, 4, 3, 2, 0 ] 

Sorting is an in-place operation, meaning .sort () method will sort the elements of a list and store the results in the same variable (in the same list), it does not create any additional variable to store the result. Moreover, if you apply sort function, save the result in a new variable, and display it. It will display “None”, as shown in the code below.

L1 = [2, 6, 8, 9, 1]
L2 = L1.sort()
print (L2)
None

print (L1)
[1, 2, 6, 8, 9]   # list is sorted because L1.sort() was applied

Using sorted ( ) function

There is a way to store the sorted list in a brand new variable, using sorted() function. Let’s see how you can use it.

The syntax for sorted function:
sorted ( iterables, reverse = Boolean_value)
* Iterables: could be a list or any other sequence
* reverse = [ False for sorting in ascending order (Default value) | True for sorting in descending order. ]

The value of reverse argument is False by default, so even if you do not explicitly provide reverse, it is going to sort items in ascending order.

month_seq = [7,8,9,10,11,12,1,2,3,4,5,6]
New_month_seq = sorted(month_seq)
Sorted_in_descending = sorted(month_seq, reverse = True)

print (month_seq)
[7,8,9,10,11,12,1,2,3,4,5,6]

print (New_month_seq)
[1,2,3,4,5,6,7,8,9,10,11,12]

print (Sorted_in_descending)
[12,11,10,9,8,7,6,5,4,3,2,1]

Sequence unpacking method

Sequence unpacking is an efficient method to assign the contents of a list with two or more variable in a single line. It uses an asterisk (*) key, also known as sequence unpacking operation in python, to group multiple elements in one variable. We will understand this with an example

Note: first, middle and last are the names of variables.

new_list = [ 2, 6, 7, 9 ]
first, *middle, last = new_list
first -> 2
middle -> [6,7] 
last -> 9 

As you can see the above result, Python assigns the value of the first variable with 2, last variable with 9 and the remaining elements got assigned to the middle variable.

Another example,

*all, last = new_list

all 
2, 6, 7  

last
9

In the above example, variable all has been assigned with [ 2, 6, 7] while variable last holds 9.


Membership function associated with a list in Python

Membership function in python finds the presence of a particular element in the list, whether a particular element is available or not. It will return True or False value accordingly. Membership function uses “in” as the keyword to verify the contents.

new_list = [ 2, 6, 7, 9 ]

2 in new_list 
True

5 in new_list
False

Python List Video Part-2


Commonly used list methods

Till now, we have understood various methods for list comprehension. Now in this last section, we will see various list function that is commonly used in day to day life. Some of the function are mentioned below.

my_list.clear ()  # to clear all elements of the list 
my_list.count (elem)  #  count the repetition of a particular element 
len (my_list)  #  to calculate the number of elements in the list 
my_list.reverse ()  #  reverse the list elements 
list2 = my_list.copy ()  #  copy existing list to new list 
del my_list  #  delete the complete instance of a list 

2 Dimensional or Nested List

Until now we had learnt about the simple 1D list, which means every element in the list are in one dimension (one value) like x = [1, 2, 3, 4].

Now, we are going to understand about two-dimensional lists. A list can be identified as a 2D list when its elements are itself a list. They are also known as nested list i.e list inside a list.

For instance, if we are interested to find the length of this list (y) it will produce a result of 4 because the internal list acts as a single element.

y = [1, 2, 3, [4, 5, 6] ] 
len (y)  # to calculate the length of a list
4 

Accessing elements in 2d list

List comprehension works pretty much the same way as it works for a normal list. We will see how to access the list element using the index method.

y = [1, 2, 3, [4, 5, 6]] 
y[0] will be 1 # value at index 0
y[1] will be 2
y[2] will be 3 and
y[3] will be [4,5,6]  

Now to access internal list using the index method we will use the following method

y[3][0] will be 4  # to get 3rd element of the main list followed by 0th element of 3rd

# Similarly others,
 y[3][1] will be 5
 y[3][2] will be 6 

Keep Learning and Keep Growing !!

2 thoughts on “Python List datastructure”

How did you like the content

Scroll to Top