Python Lists – A complete guide with Examples

In this python article, we will discuss the about Lists data type and discuss the usability and the operations possible on a list like slicing, deletion, iteration, etc.

1. What is a List in Python?

The List is a data type that acts as a container and holds different objects together in order.

A list is a mutable object, which means that it can be modified once it’s created. It can be used to store numbers, strings or any other data types together in order.

We can even hold elements of different data types in a list in Python.

Example of lists are: 

[1, 7, 3, 8, 5]
['a', 'b', 'c', 'f']
[2, 'abcdef', 9, 10]

2. How to create a Python list?

In Python programming, we can create a list by placing all the list elements inside square brackets [] that are separated by a comma.

There is no limit on the number of items that a list can hold.

# empty list
list_val = []

# list of numbers
list_val = [1, 2, 3, 4, 5]

# list with mixed data types
list_val = [1, "Hello", 1.234]

We can also declare nested list which means a list within a list and that can be defined as follows.

# nested list
list_val = ["codingeek", [1, 2, 3], ['.', '*']]

3. How to access List elements?

We can use indexes to access an element in Python lists. Indexing can be of two types positive indexing and negative indexing. Let’s discuss both of index types in detail.

Python-String-Index
Positive and negative indexes in Python Lists

3.1. Positive Indexing in Python

Data in the ith index can be accessed by using listname[i]. Here the listname is the name of the list and i is the index that is to be accessed.

The index number of lists starts from zero and goes up to n-1, where n is the number of elements in the list.

Let’s take some examples to clear the concepts.

list_val=[2, 3, 4, 5, 6]
print(list_val)
print(list_val[0])

#updating value at second index
list_val[3]=9         
print(val[1],val[3])  
print(list_val)
Output
[2, 3, 4, 5, 6]
2
3 9
[2, 3, 4, 9, 6]

In the above example, we can see that the elements of the list list_val=[2,3,4,5,6] have indices 0, 1, 2, 3 and 4 respectively.

Printing list_val would print the whole list whereas printing list_val[i] would print the element in the ith index. The use of lists having integers is pretty much the same as that of using an array in C/C++. But in C++, we can only store items with the same data type. But this is not a problem with the Python list.

The lists in Python are also mutable. This can be seen as list_val[3] was changed from 4 to 9, and the output confirms it without any errors.

We can use lists for different data types as well.

# Holds multiple type of objects in a list
list_item=["str1", 3, "string2", 5, 6, 9.9] 
print(list_item[0])
Output
str1

3.2. Negative Indexing in Python

Similar to positive indexing in Python we can also use negative indexes to access the elements of a list. We use negative indexes when we want to access the element from the end.

Let’s go through some examples to to access a list elements using negative indexes.

list_val=[1, 2, 3, 4, 5, 6]

# acess last element
print(list_val[-1])

# acess 5th last element
print(list_val[-5])

# acess last 3 elements
print(list_val[-3:])

# acess 4th last to second last element
print(list_val[-4:-1])

# acess from first tilll second last element
print(list_val[:-1])
Output
6
2
[4, 5, 6]
[3, 4, 5]
[1, 2, 3, 4, 5]

4. Different Operations on Python Lists

Now, we shall discuss some of the important in-built functions that we can use on a list. We will implement each of them with small examples to understand better.

So let’s get started with one of the most widely used and important operation named Slicing.

4.1. Slicing

Python lists have a special advantage of slicing in which a portion or a section of a list can be simply obtained using the indexes.

Taking a look at the following example:

list_val=[1,3,4,5,6,8]

#This prints elements with indices 0,1,2
print(list_val[0:3])    

#Similarly, upto indices less than 5, i.e. 0,1,2,3,4
print(list_val[:5]) 

#Only index 1
print(list_val[1:2])

# from second index till the end
print(list_val[2:])    
Output
[1, 3, 4]
[1, 3, 4, 5, 6]
[3]
[4, 5, 6, 8]

From the above example, we can see that

  • if we print list_val[i:j], the output would be the elements from the index i to index j-1.
  • for list_val[i:] the output would be from the index i to last element and
  • for list_val[:j], it will be from the 0th index to index j-1.

4.2. Negative Indexing and Slicing

The indexing can also be done from the last index. If we want to access the elements from the reverse order, we use this method.

Similarly, slicing can also be done by specifying negative indices. This can be cleared out from this example.

a=[1,3,4,5,6,8]

#prints 1st element from the reverse direction 
print(a[-1]) 

# Prints 4th last element
print(a[-4])

#prints the 4th and 3rd element from the last, i.e. indices 2,3
print(a[-4:-2])

# Prints last 5 elements
print(a[-5:])

# Both statements are same and print 2,3 and 4th element
print(a[-5:4])
print(a[1:4])
Output
8
4
[4, 5]
[3, 4, 5, 6, 8]
[3, 4, 5]
[3, 4, 5]

From the above example, you can see that if we print a[-i], the output would be the ith element from the end of the list.

Slicing is just the same, but just with negative indices.

We can also mix up negative and positive indices. Only thing we have to remember is that if the number is negative then start counting backwards.


5. How to Delete Elements in Python List?

In Python, we can use del keyboard to delete a single element or the entire list.

Let’s implement an example to delete specific elements from a list and also to delete the entire list.

list_val=[1,3,4,5,6,8]
#deletes element in index 2
del list_val[2] 
print(list_val)

#deletes elements with indices 3,4
del list_val[3:5] 
print(list_val)

#deletes last element
del list_val[-1]
print(list_val)

#deletes entire list
del list_val
print(list_val)
Output
[1, 3, 5, 6, 8]
[1, 3, 5]
[1, 3]
Traceback (most recent call last):
   File "", line 1, in 
 NameError: name 'list_val' is not defined

From the above example we can see that we can not access the list anymore once it is deleted and it throws the error.


6. How to take a list as input in Python?

Now we come to the next question. How to take a list as an input? Suppose we have a sequence of numbers separated by spaces, which we want to store in a list by taking user input. How to achieve this?

Let’s have an overview of the process. As previously stated, Python takes the user input line by line in string format.

So it takes a sequence of numbers that are separated by spaces, then we have to take out the numbers between those spaces and convert them into integers. This process can be done in many ways.

The easiest to understand is –

s = input()
b = map(int, s.split(" "))
a = list(b)
print(a)
Input
2 4 5 6
Output
[2, 4, 5, 6]

Now let’s just have an explanation of what we did there. There are 3 steps involved here

  • Line 1 – The user input 2 4 5 6 is stored in a string format, i.e. “2 4 5 6” in a variable ‘s’.
  • Line 2 – The input string “2 4 5 6” is then split by spaces (If you look at the split() function, the parameter passed is a space character). Then this string format is mapped to integer format using the map() function and is stored in a variable b.
  • Line 3 – The result b is finally converted into a list and stored in the variable a.

The 3 lines of the previous program can be written in just one line. The program for that would be as folloows.

a = list(map(int, input().split()))
print(a)
Input
2 4 5 6

Output
[2, 4, 5, 6]

Please go through the explanation once more if there are any doubts.

Note: Here we don’t pass any parameters in the split() function because the default character which it uses to split is the space character. Hence, it is not necessary to pass the space character.

Note: Above examples are only for int but we can do the same for floats, strings, etc, and can use the input() method as per our requirements to initialize the list. We can also use it multiple times to initialize a list of mixed objects.


7. Built-in Functions frequently used for lists

There are some functions that can be applied to a list. Consider a list with name list_name

  1. max(list_name): It returns the maximum value from the given list.
  2. min(list_name): It returns the minimum value from the given list.
  3. len(list_name): It returns the length of the list.
  4. list(list_name): It can be used to assign the whole list to other variables.
  5. sort(): Sorts the list in ascending order.
  6. reverse(): Reverse the order of the list.
  7. append(): Add an element to the end of the list.
  8. extend(): Add all elements of a list to the another list.
  9. insert(): Insert an item at the defined index.
  10. remove(): Removes an item from the list.
  11. pop(): Removes and returns an element at the given index.
  12. clear(): Removes all items from the list.
  13. index(): Returns the index of the first matched item.
  14. count(): Returns the count of the number of items passed as an argument.
list_val=[1, 2, 3, 4, 5, 6]

print(max(list_val))
print(min(list_val))
print(len(list_val))

new_list = list(list_val)
print(new_list)

new_list.reverse()
print(new_list)

new_list.sort()
print(new_list)
Output
6
1
6
[1, 2, 3, 4, 5, 6]
[6, 5, 4, 3, 2, 1]
[1, 2, 3, 4, 5, 6]

8. How to iterate on a List

Iteration is done by using loops. Here is an example of an array arr, using for loop

arr = list(map(int, input("Enter numbers").split()))

print("Access with index")
for i in range(0, len(arr)):
  print("index", i, " - ", arr[i])


print("Access without index")
for item in arr:
  print(item)
Input
2 4 5 6
Output
Access with index
index 0  -  2
index 1  -  4
index 2  -  5
index 3  -  6
Access without index
2
4
5
6

9. List Membership Test

We can test if an item exists in a list or not, using the keyword in.

list_val = ['c', 'o', 'd', 'i', 'n', 'g', 'e', 'e', 'k']

print('p' in list_val)
print('k' in list_val)
print('c' not in list_val)
Output
False
True
False

10. Conclusion

In python ,we have some other operations or methods on lists are used to add an element, add another list, remove an element, sort the list, check the existence of an element and other basic functionalities.

We can find out them at official documentation for a complete list of methods and functionalities.

  • How to access a list with positive and negative indexing?
  • Different operations on the list.
  • How to delete elements from a list?
  • Some built-in functions for the list.
  • How can we iterate through a list and the list membership test.

Helpful Links

Please follow the Python tutorial series or the menu in the sidebar for the complete tutorial series.

Also for examples in Python and practice please refer to Python Examples.

Complete code samples are present on Github project.

Recommended Books


An investment in knowledge always pays the best interest. I hope you like the tutorial. Do come back for more because learning paves way for a better understanding

Do not forget to share and Subscribe.

Happy coding!! ?

Recommended -

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x
Index