Python Lists | The No 1 Ultimate Guide

Contents hide
1. Python Lists | The No 1 Ultimate Guide

In this tutorial we will be taking a look at Python Lists,

While going from beginner level practices to a higher level in a progressive manner.

Firstly, let us understand what these lists are, why do we use them and how to make proper use of them.

Author: Sahil (You can also author posts on thatascience. Contact us)

Last Modified: 9 Jan, 2022

Python Lists Tutorial

What are Python Lists?

  • Python Lists can store multiple values/items in a single variable.
  • Basically, Python lists is a data structure that is mutable and ordered.
  • Each element inside these Python lists is an item.
  • It is also possible to store multiple data types in the same data structure. I.e., we can have integers, strings, characters etc. in the same data structure.

The most important thing to take away from this explanation is the fact that Python Lists are mutable

Meaning that once created the lists values can still change.

Also, Python Lists are in order. Meaning that the sequence of lists is persistent.

Why do we use Python Lists? What is the need of lists in python?

  • Lists have been an increasingly popular data structure amongst developers and is the most commonly used data structure in Python.
  • Lists provide us with extremely useful methods like count(), insert(), extend() etc. That help us in formatting the data.
  • As stated earlier, we can store multiple data types in lists and hence it is preferred over the alternatives (arrays for example).
  • Lists are also mutable meaning we can change the values even after we allocate items to the list.

How do we create Python Lists?

  • Python lists are created by placing all the items in between two square brackets [ ].
  • All these items placed in between the square brackets must be separated by commas ( , ).
  • These items can be of any datatype that you want as lists can store multiple datatypes.

Ex. new_list = [1, 2, 3, 4]

new_list2 = [1, “different data type”, 3, 4]

Different operations performed on a list | Python Lists Methods

Now we will talk about the different operations that can we can perform on a list. This is known as list methods.

For these examples let us consider a simple list like my_list = [‘a’ , ’b’ , ’c’] on which we will perform our operations.

append() : Method used to add an item to the end of the list

Syntax : my_list.append(“d”)

Result : The ‘d’ element gets added to the end of the list

my_list = ['a' , 'b' , 'c']
#Using append method
my_list.append('d')
print(my_list)
['a', 'b', 'c', 'd']
 

clear() : Method used to remove all items from the list

Syntax : my_list.clear()

Result : every element from the list ‘my_list’

my_list = ['a' , 'b' , 'c']
#Using clear method
my_list.clear()
print(my_list)
[]
 

copy() : Method used to return a copy of the list

Syntax : x = my_list.copy()

Result : copies all the elements of list ‘my_list’ into ‘x’

my_list = ['a' , 'b' , 'c']
#Using copy method
x = []
x = my_list.copy()
print(x)
['a', 'b', 'c']
 

count() : Method used to return the number of times a specified value has been repeated in the list.

Syntax : x = my_list.count(“a”)

Result : ‘x’ will store the value of how many times the item ‘a’ has been repeated in the list ‘my_list’

my_list = ['a' , 'b' , 'c']
#Using count method
print(my_list.count('a'))
print(my_list.count('z'))
1
0
 

extend() : Method used to add the elements of another list to the end of the current list

Syntax : my_list.extend(x)

Result : ‘my_list’ gets extended by all the values inside the list ‘x’

my_list = ['a' , 'b' , 'c']
#Using extend method 
my_list.extend(x) 
print(my_list)
['a', 'b', 'c', 'a', 'b', 'c']
 

Index() : Method used to return the index of the first item with the specified value

Syntax : x = my_list.index(“c”)

Result : variable ‘x’ will store the position of the item ‘c’ in the list ‘my_list’

my_list = ['a' , 'b' , 'c']
#Using index method
x = my_list.index('c')
print(x)
2
 

Insert() : Method used to insert an item at the specified position

Syntax : my_list.insert(2, “hello”)

Result : adds the value “hello” at the specified positions ‘2’ in ‘my_list’

my_list = ['a' , 'b' , 'c']
#Using insert method
my_list.insert(2,'hello')
print(my_list)
['a', 'b', 'hello', 'c']
 

pop() : Method used to remove an item at the specified position

Syntax : my_list.pop(2)

Result : will pop the value at position ‘2’ in ‘my_list’

my_list = ['a' , 'b' , 'c']
#Using pop method
my_list.pop(2)
'c'
 

remove() : Method used to remove the first item with the specified value

Syntax : my_list.remove(“b”)

Result : will remove the first occurrence of the item ‘b’ from ‘my_list’

my_list = ['a' , 'b' , 'c']
#Using remove method
my_list.remove('b')
print(my_list)
['a', 'c']
 

reverse() : Method used to reverse the order of the list

Syntax : my_list.reverse()

Result : Reverses the order of the values in the list

my_list = ['a' , 'b' , 'c']
#Using reverse method
my_list.reverse()
print(my_list)
['c', 'b', 'a']
 

sort() : Method used to sort the items of a list

Syntax : my_list.sort() (use my_list.sort(reverse = True) for reverse order)

Result : Sorts the items in ‘my_list’

my_list = ['a' , 'b' , 'c']
#Using sort method
my_list.sort()
print(my_list)
['a', 'b', 'c']
 

List Comprehension in Python

  • List comprehension is the practice of using a shorter syntax
  • When you want to create a new list based on the values of an existing list.
  • With the help of list comprehensions, it is possible to avoid writing 3-4 lines of code for looping through a list.
  • This saves up a lot of time for the developer and also keeps the code clean

The use of List Comprehension is made much clearer with the following example:

my_list = ['a' , 'b' , 'c']
# List comprehension
new_ls = [i+i for i in my_list]
print(new_ls)
['aa', 'bb', 'cc']
 

Nested Lists in Python

  • As we have discussed before, a list can contain any type of object in it
  • Which also means a list is also able to contain another list entirely.
  • It is also possible for that sublist to contain more lists and so on. These are known as nested lists (basically one or more lists contained inside a parent list)
  • Nested lists have the following syntax :
  • My_list = [‘a’ , ‘b’ , [‘c’, ‘d’], ‘e’]
  • In this example the list [‘c’, ‘d’] is a sublist of ‘my_list’
  • And these items can be accessed using similar commands to what we used for a regular list
  • Iterating through a nested list is made simple with the help of this example:
# Let us consider a dummy nested list which contains the names of employees, their ID and their salary

list = [["Akhilesh", 60, 60000], ["Avinash", 22, 70000],  
        ["Harsh", 30, 90000], ["Ramesh", 440, 100000]] 
  
# looping through nested list we get 

for employees in list: 
    print(employees[0], "Employee ID :", employees[1], 
          "is being paid", employees[2], "Rs.")
Akhilesh Employee ID : 60 is being paid 60000 Rs.
Avinash Employee ID : 22 is being paid 70000 Rs.
Harsh Employee ID : 30 is being paid 90000 Rs.
Ramesh Employee ID : 440 is being paid 100000 Rs.
 
# Let us consider a dummy nested list which contains the names of employees, their ID and their salary

list = [["Akhilesh", 60, 60000], ["Avinash", 22, 70000],  
        ["Harsh", 30, 90000], ["Ramesh", 440, 100000]] 
  
# looping through nested list we get 

for employees in list: 
    print(employees[0], "Employee ID :", employees[1], 
          "is being paid", employees[2], "Rs.")
Akhilesh Employee ID : 60 is being paid 60000 Rs.
Avinash Employee ID : 22 is being paid 70000 Rs.
Harsh Employee ID : 30 is being paid 90000 Rs.
Ramesh Employee ID : 440 is being paid 100000 Rs.
 

Using Python lists as different data structures

  • One more advantage of using lists comes from the fact that how easily they can transform into another data structure in python.
  • Due to the number of different methods provided in the list data structure in python,
  • It is possible to use the lists as a stack or queue (both being primitive data structures that may be used individually)

The following sections will explain more on the topic:

Using Python Lists as a Stack:

  • We know that Stack is a LIFO (Last in first out) data structure. Meaning that the element that is added to the last is the first one to be ‘popped’ from the list.
  • To add an item to the stack we can use the List method append()
  • To remove an item from the stack we can use the List method pop()
stack = [] #initializing stack
stack.append('a') #adding values to the stack using append method 
stack.append('b')
stack.append('c')
stack.append('d')

print(stack)
['a', 'b', 'c', 'd']
stack.pop() #pop method will always remove the newest value that was added to the stack hence the list behaves like a stack in LIFO order
'd'
print(stack) #after elements have been 'popped' from the stack
['a', 'b', 'c']
 

Using Python Lists as a Queue:

  • Queue is a FIFO (First in First out) data structure. Meaning that the element that gets added the earliest is the first one to be ‘popped’
  • To achieve this, we can make use of collections.deque which makes it possible for us to append from both sides
  • Deque allows us to make use of the method popleft() which in turn enables us to pop elements from the starting position
  • We will similarly make use of the append() method to add elements.
from collections import deque
 
# Declaring a queue using deque
queue = deque()
 
# Adding elements to a queue using append method
queue.append('a')
queue.append('b')
queue.append('c')
queue.append('d')

print(queue)
deque(['a', 'b', 'c', 'd'])
# Using deque method popleft to pop elements from the given queue

print(queue.popleft())
print(queue.popleft())

 
print(queue) #Printing the queue after removing the elements
a
b
deque(['c', 'd'])
 

Comparing Python List to other Data Structures

  • In this section we will discuss the different alternative data structures to Python list.
  • So it is easier for you to decide when it is more suitable for you to make use of lists,
  • And when to look for an alternative.
  • For example,
  • If you want your data structure to contain unique values then making use of a set is preferable over the use of lists.
Python lists comparison with other python data structures

How do I concatenate two lists in Python?

Now, we start with the more technical part of the Ultimate Guide to Python Lists tutorial.

Let’s see how to concatenate two lists using different methods in Python. This operation is useful when we have numbers of lists of elements which needs to be processed in a similar manner.

Using Naive Method

In this method, we traverse the second list and keep appending elements in the first list,

So that first list would have all the elements in both lists and hence would perform the append

#Using naive method
l1 = [1,2,3,4,5]
l2 = [6,7,8,9,0]

for i in l1:
    l2.append(i)

print("concatenated list :", l2)
concatenated list : [6, 7, 8, 9, 0, 1, 2, 3, 4, 5]
 

Using + operator

The most conventional method to perform the list concatenation,

The use of “+” operator can easily add the whole of one list behind the other list and hence perform the concatenation.

#Using + operator
l1 = [1,2,3,4,5]
l2 = [6,7,8,9,0]

l3 = l1+l2

print("concatenated list :", l3)
concatenated list : [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
 

Using Python list comprehension

  • List comprehension can also accomplish this task of list concatenation. In this case, a new list is created, but this method is a one liner alternative to the loop method discussed above.

#Using List Comprehension
l1 = [1,2,3,4,5]
l2 = [6,7,8,9,0]

l3 = [y for x in [l1, l2] for y in x]

print("concatenated list :", l3)
concatenated list : [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
 

Access Python List Elements

There are various ways in which we can access the elements of a list.

List Index

We can use the index operator [] to access an item in a list. In Python, indices start at 0. So, a list having 5 elements will have an index from 0 to 4.

Trying to access indexes other than these will raise an IndexError. The index must be an integer. We can’t use float or other types, this will result in TypeError.

Nested lists are accessed using nested indexing.

#List Indexing Example
l1 = [1,2,3,4,5]

x = l1[2]
y = l1[3]

z = l1[3.0] #Error will be thrown as indexing value is not an int value
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-8-e43184ad035e> in <module>
      5 y = l1[3]
      6 
----> 7 z = l1[3.0] #Error will be thrown as indexing value is not an int value

TypeError: list indices must be integers or slices, not float
print(x)
print(y)
3
4

Negative indexing

Python allows negative indexing for its sequences. The index of -1 refers to the last item, -2 to the second last item and so on.

#Negative List Indexing Example
l1 = [1,2,3,4,5]

x = l1[-1]
y = l1[-5]

print(x)
print(y)
5
1

List indexing and splitting

Now, we will talk explain more in depth about list indexing in Ultimate Guide to Python Lists.

The indexing is processed in the same way as it happens with the strings. The elements of the list can be accessed by using the slice operator [].

Index starts from 0 and goes to length – 1.

The first element of the list is stored at the 0th index,

The second element of the list is stored at the 1st index, and so on.

We can get the sub-list of the list using the following syntax.

  • The start denotes the starting index position of the list.
  • The stop denotes the last index position of the list.
  • The step is used to skip the nth element within a start:stop

Unlike other languages, Python provides the flexibility to use the negative indexing also. The negative indices are counted from the right. The last element (rightmost) of the list has the index -1; its adjacent left element is present at the index -2 and so on until the left-most elements are encountered.

Ways to Iterate Through List in Python

This part of the Ultimate Guide to Python lists will talk about the different ways in which we could iterate a given list.

Iterate through list in Python using range() method

Python’s range() method can be used in combination with a for loop to traverse and iterate over a list in Python.

The range() method basically returns a sequence of integers i.e.

It builds/generates a sequence of integers from the provided start index up to the end index as specified in the argument list.

  • start(upper limit): This parameter is used to provide the starting value/index for the sequence of integers to be generated.
  • stop(lower limit): This parameter is used to provide the end value/index for the sequence of integers to be generated.
  • step(optional): It provides the difference between each integer from the sequence to be generated.

The range() function generates the sequence of integers from the start value till the end/stop value,

But it doesn’t include the end value in the sequence i.e. it doesn’t include the stop number/value in the resultant sequence.

#Using range method
l1 = [1,2,3,4,5]
 
for x in range(len(l1)): 
    print(l1[x]) 
1
2
3
4
5
 

Iterate through list in Python using a for Loop

Python for loop can be used to iterate through the list directly.

#Using for loop
l1 = [1,2,3,4,5]
 
for x in l1: 
    print(x) 
1
2
3
4
5

List Comprehension to iterate through a list in Python

Python List Comprehension is an indifferent way of generating a list of elements that possess a specific property or specification i.e.

It can identify whether the input is a list, string, tuple, etc.

#Using List Comprehension
l1 = [1,2,3,4,5]
 
[print(x) for x in l1] 
1
2
3
4
5
[None, None, None, None, None]

Python NumPy to iterate through List in Python

Syntax for numpy.arange() function:

  • start: This parameter is used to provide the starting value/index for the sequence of integers to be generated.
  • stop: This parameter is used to provide the end value/index for the sequence of integers to be generated.
  • step: It provides the difference between each integer from the sequence to be generated.

The numpy.nditer(numpy_array) is a function that provides us with an iterator to traverse through the NumPy array.

#Using Numpy arange
import numpy as np
 
n = np.arange(10)
 
for i in np.nditer(n): 
    print(i) 
0
1
2
3
4
5
6
7
8
9

Python enumerate() method to iterate a Python list

Python enumerate() function can be used to iterate the list in an optimized manner.

The enumerate() function adds a counter to the list or any other iterable and returns it as an enumerate object by the function.

Thus, it reduces the overhead of keeping a count of the elements while the iteration operation.

  • start_index: It is the index of the element from which the counter has to be recorded for the iterating iterable.

 

#Using Enumerate method
l1 = [1,2,3,4,5]
 
for x, l2 in enumerate(l1): 
    print (x,":",l2)
0 : 1
1 : 2
2 : 3
3 : 4
4 : 5

Conclusion of Python Lists Tutorial

  • So, there we have it. In this Python List Tutorial, we have gone through all the important concept concerning lists
  • Understood the all the different operations that we can perform on a list.
  • Also talked about how we can avoid writing lengthier codes with the help of list comprehensions.
  • We learned about Nested Lists and how we can make use of lists to simulate different primitive data structures.
  • We also discussed the other kind of in-built data structures that python has to offer.
  • After this tutorial, you are ready to perform all of these functions on a list yourself.
  • Now why not try on your own.

Leave a Reply

Your email address will not be published.