Pages

Wednesday, December 30, 2020

Working with Lists in Python

Lists in Python

Like an array, List is a collection of data (of different data types). Lists are specified using square brackets. 

Lists are very helpful when working with data in Python. Below are some of the features of Lists. 
  • Lists can hold data of different data types. 
  • Lists can be amended.
  • Data in the list can be accessed by using index.
  • Lists can hold duplicate data. 

In this post, we will see how to access, append or remove the data in Lists and how to use different list methods. 

Creating List in Python

Before we go on to different methods of lists, Let us see How to create a List in Python?

Like any other variable in python, List is created when the data is assigned with in square brackets. 

How to create a list in Python

In the above example, 'a_list' is created with the data and 'b_list' is created with no data. 

Accessing the data in a List

How to access the individual elements of Lists? Elements in the Lists can be accessed using index. Index starts with '0' and incremented by '1'. 

Index of a List in Python

Elements of a List can be accessed from the last element with the negative index value. As we can see above, Index of last element would be '-1'. 

If we need to retrieve the second element ("TWO"), index '1' or '-4' needs to be mentioned within square brackets. 

E.g.: 

print(a_list[1]) #prints the second element of a list

print(a_list[-4]) #prints the fourth element from end of a list

Retrieve Index of an element

We have seen how to access the elements using an index, If we know the element and need to know the index, Method 'index()' would be helpful. One thing to note is, it always returns the first index if the element is present multiple times in the list. 

Retrieve index of an element in List - Python

In the above example, '2' is present twice in the list. But, only one index (first occurrence '1') will be returned.

Print list in Python

Adding data to a List

One of the features of a List is the data can be amended. Using append() method, we can add the data to a list. data that needs to be added is to be passed as a parameter to append() method. 

Add new data to a List in Python

In the above example, we are passing "FOUR" to the method 'append()'. This should be added towards end of the list. 

If we notice, "FOUR" is already present in the list. Python allows duplicate data in the list and "FOUR" should be added successfully and printed like the below. 

Print in Python

In the above example, we are only adding one element at a time. If we have another list that needs to be added, this needs to be done with in a loop to add all of these elements using append. What if the list have large number of elements? 

Method 'extend()' can be used to append one list to the other. This method accepts a list (that is to be added) as an argument.

Extend a List in Python

In the above example, data in b_list would be added to a_list. 

Print a list in Python

Removing data from a List

Data can be removed from a list by using remove() method. Similar to the append() method, data that is passed as a parameter would be removed from a List. 

Remove data from a list in Python

In this example, we have two entries with 'FOUR'. And, first occurrence would be deleted from a list. 

Print List in Python

Copy data from one List to other

Like copying data from one variable to other, copying one list to other becomes essential. 

Is copying data from one list to other as simple as copying data from one variable to other? 

Simple answer is 'No'. 

Copying List in Python

In the above example, 
  • Line - 3: 'b_list = a_list', a_list doesn't actually copied over to b_list. b_list would be referencing a_list and any changes to a_list or b_list would reflect for both these. 
  • Lines - 5 & 6: We are appending '6' to b_list and 'SEVEN' to a_list. 
  • Lines - 8 & 9: Both lists should print the same result. 
Print List in Python

To avoid this issue, using copy() method would help to copy the data from one list to other. Let's see how this works using the same example. 

Copy data from one list to other in Python

  • Line - 3: we are using 'a_list.copy()' to copy the data, copy() method doesn't require any arguments.
Print list in Python

One other way to do this is by using function list(). This can be to copy the data from a list, tuple or by passing the data directly. 

Using list function to copy data in Python

In the above example, Lines from 5 to 8 should work in the same way and create list with the data passed.

Clear data from a List

Clearing data from a list can be done using 'clear()' method. This method doesn't require any arguments to be passed and clears the referencing list. 

Clear data from a List in Python

Retrieve the number of occurrences of an element

We know that Python allows duplicate values in the list. If we need to know the number of occurrences of an element in a list, we can use method 'count()'. We need to pass the element value as an argument to this method.

Count the number of occurrences of an element in the list

In the above example, '2' is present '3' times. 

Count the number of occurrences of an element in a List

Retrieve & Delete the value by Index

In the beginning we have seen how to access the values in a list by using index. Let's say if we need to retrieve the value by index and delete this from the list, 'pop()' method is helpful for doing this. 
  • 'pop()' accepts index as an argument and it returns the value in the specific index. 
  • Once the value is deleted, Python would automatically adjust the index, value in the next position would now be referred with this index. 
Retrieve & Delete the value from a list using pop() in Python

In the above example,
  • Line - 4: value '2' (at index 1) should be returned and deleted from the list.
  • Line - 5: value '3' would now be at index '1' and should be returned and deleted from the list.
Print list in Python

Sorting a List

Lists doesn't necessarily hold the data in the order (ascending or descending). But, if we need to sort the data in a list, Method 'sort()' is useful. With default parameters, this method sorts the data in ascending order and by passing 'reverse=True' data is updated in reverse order. And, method reverse() is useful to sort the data in reverse order.

Sort a list in Python



In the above example, 
  • Line-3: With no arguments passed, list would be sorted in ascending order.
  • Line-8: with 'reverse=True', list would be sorted in descending order. passing 'reverse=False' would work like default and data is sorted in reverse order.
  • Line-14: Data would be sorted in reverse order of index.
Print list in Python

One thing to note here is, sort() would only work with data of same data type in a list. If there are different data types present (like int and str), sort() would fail.

The above 'sort()' method updates the same list. If we need to sort the data and move it to the new list (and leave the original as is), we can use the function 'sorted()'. This accepts a list as an argument and returns sorted list. There is an optional parameter 'reverse', by passing 'True' to this parameter would sort the data in descending order.

Sorted() in Python


Print list in Python

Hope the above details were a bit of help to you in understanding more about Lists in Python.


If you have any Suggestions or Feedback, Please leave a comment below or use Contact Form.

No comments:

Post a Comment

Exception Handling in Python (try - except-else-finally)

Exception Handling in Python Exception handling is key for any programming language. When an exception occurs Python interpreter stops execu...