Everything you need to know about lists in python

Introduction

Lists are one of the most common data structures used in python. When you learn to create your own programs in python you surely use the concept lists extensively since it is simple to create and efficient to store all kinds of data types including integers, strings, floating numbers, etc. This article solely focuses on the complete guide to lists in python.

Things you'll learn:

  • What are lists in python and how to create them?
  • Advantages of lists.
  • Accessing elements in a list.
  • Adding and modifying elements in a list.
  • Removing elements from a list.
  • Sorting a list.
  • Finding the length of the list.
  • Looping through a list.
  • Creating numerical lists.
  • List comprehension
  • Slicing a list. 
  • Merging two lists

Lists in python

Lists in python are a series or collection of data that can be the same or different, which means, we can store all kinds of data inside a python list no matter it is a number or a character, or even a function. The list can be created using square brackets ([ ]) with commas separating each element.

languages = ["Python","Java","JavaScript","C"]
print(languages)

output:
['Python', 'Java', 'JavaScript', 'C']

By printing a list you'll see the same representation of the list as you created.

Advantages of lists in python

  1. Lists in python are mutable, which means, it can be changed and manipulated throughout the program.
  2. The list can hold multiple data types together.
  3. Indexable
  4. Easily accessible

Accessing elements in a list

In the above case, we printed the list directly using the print function and the list name, but what if you want to access individual elements from a list? since lists are ordered collections of data you can access any elements from a list using its specific index. 

  • 📓 Note: The index of a list always starts from 0 to n-1

languages = ["Python","Java","JavaScript","C"]
print(languages[0])

output:
Python

Here we are printing the zeroth index of the list using the list name along with the index specified inside square brackets, "Python" is in the zeroth index will be printed to the console.

languages = ["Python","Java","JavaScript","C"]

print("This is the first element of the list:",languages[0])
print("This is the second element of the list:",languages[1])
print("This is the third element of the list:",languages[2])
print("This is the fourth element of the list:",languages[3])

output:
This is the first element of the list: Python This is the second element of the list: Java This is the third element of the list: JavaScript This is the fourth element of the list: C

So this is how you can access elements inside a list in python, but hold on, how can you access the last elements from a huge list of items in python, if the list is large it is way hard to find the index of the last elements by counting, although we can access the last elements in a list using the negative index,

languages = ["Python","Java","JavaScript","C"]
print(languages[-1])
print(languages[-2])

output:
C
JavaScript

Modifying elements in a list

Can we change elements once we created a list? Yes, we can. You can simply modify the elements of the list by assigning values to a specific index.

letters = ["a","b","c","d"]

letters[0] = "z" # Assigning new value to the zeroth index

print(letters)

output:
['z', 'b', 'c', 'd']

You can see a is disappeared from the list, this is because the first item in the zeroth index is being overwritten by the new item, z in this case. You can change any value in the list not just the first.

Adding elements to a list

Sometimes you want to add new items to a list throughout the program, for instance, if you want to add a new data point for data visualization, it might need to insert the data into a list. In python, you can simply add an element to the last position of the list using the append() method.

letters = ["a","b","c","d","e"]

letters.append("f")

print(letters)

output:
['a', 'b', 'c', 'd', 'e', 'f']

⚈ Inserting elements to a specific index:

You can insert elements to the list in any position using the insert() method. Simply specify the index and the value you want to insert.

letters = ["a","b","c","d","e","g"]

letters.insert(5, "f")

print(letters)

output:
['a', 'b', 'c', 'd', 'e', 'f', 'g']

In this example, f is inserted between e and g in the fifth index. This function actually creates a space in the list by shifting the elements once placed to the right for storing the new items.

Removing elements from a list

So we discussed inserting items to a list, deletion of elements is also important as insertion because in some cases you need to delete the unwanted elements from a list. You can delete elements from a list in different ways:

⚈ Deleting elements using the del statement

To delete an element from a list using its position we can use the del statement.

letters = ["a","b","c","d","e","g"]

del letters[0]

print(letters)

output:
['b', 'c', 'd', 'e', 'g']

⚈ Removing an element using the pop() method

The pop method removes the last item of a list

letters = ["a","b","c","d","e","g"]

letters.pop()

print(letters)

output:
['a', 'b', 'c', 'd', 'e']

⚈ Poping elements using index

letters = ["a","b","c","d","e","g"]

letters.pop(0)

print(letters)

output:
['b', 'c', 'd', 'e', 'g']

⚈ Removing elements by value

For removing elements by specifying the value, we can use the remove() method in python. Simply give the element you want to remove from a list inside the remove() method.

letters = ["a","b","c","d","e","g"]

letters.remove("d")

print(letters)

output:
['a', 'b', 'c', 'e', 'g']

Sorting a list

Python allows you to sort lists in alphabetical order using the sort() method. This method is really helpful in some cases where you want to sort the list of names of users, places, objects, etc,

names = ["alex", "jack", "zeth", "boby"]

names.sort()

print(names)

output:
['alex', 'boby', 'jack', 'zeth']

The list is now in alphabetical order, here if you sorted the list once you cannot change it to the original order. So in order to obtain the original order of the list again, we can use the sorted() instead of the sort method for sorting the list temporarily.

names = ["alex", "jack", "zeth", "boby"]

sorted_names = sorted(names)

print("This is the sorted names:", sorted_names)
print("This is the original names:", names)

output:
This is the sorted names: ['alex', 'boby', 'jack', 'zeth']
This is the original names: ['alex', 'jack', 'zeth', 'boby']

You can also sort the list in reverse alphabetical order by simply enabling the reverse to true inside sort method.

names = ["alex", "jack", "zeth", "boby"]

names.sort(reverse=True)

print(names)

output:
['zeth', 'jack', 'boby', 'alex']

Finding the length of the list

Finding the length of the list is really useful in many cases like finding the total number of users who registered their account on your website, the total number of data stored in your database, etc. In python, you can find the length of a list using len() method.

names = ["alex", "jack", "zeth", "boby"]

print(len(names))

output:
4

Since the list has four items, the length is 4

Looping through a list

We have learned how to access elements from the list using the index, but it is not possible for you to specify all the indexes of a list containing thousands of elements. In that case, we'll use a loop in order to access every element inside a list. We can use a for loop for this purpose since it is most commonly used in programming.

names = ["alex", "jack", "zeth", "boby"]

for name in names:
   print(name)

output:
alex
jack
zeth
boby

If you run this code you'll see the items inside the names list are printed to the console one after the other. Here in the initial processing of the for loop, python assigns the first value of the list which is "alex" to name, and then reads the next line which is print(name), after printing the value it again assign the next value which is "jack" to name and print it, this process will continue until all the elements in the list are visited. This process is known as iteration.

Looping using the len() and range() methods

We saw how to loop through a list simply, there is another way for looping through a list which is using the len() and range() method in python. so let's see how this can be done.

names = ["alex", "jack", "zeth", "boby"]

for name in range(len(names)):
    print(names[name])

output:
alex
jack
zeth
boby

This will print the same output as in the previous case, but here we used the range() method which tells how far need to iterate, for instance if we give 10 inside the range function in a loop the loop will run 10 times. So here we specified the length of the list which is 4, so the loop will run 4 times. Then we gave names[name] which print each item in the list by index.

  • 📓 Note: Be sure to give indentation to every statement inside a for loop or else it will throw an error or doesn't give the desired output. the standard indentation is 4 spaces.
  • Give a colon after the for loop statement.

Creating numerical lists

So far we deal with a list of character types or strings, now we'll head into numerical lists. Storing numbers in a list is useful in many cases. In data analysis and visualization, you'll almost work with the list of numbers all the time. In python the range() function discussed earlier can be used to create a list of numbers.

# Creating a list of numbers
numbers = list(range(1,10))

# Creating a list of even numbers
even_numbers = list(range(2, 11, 2)) # Start from 2 and adds 2

# Creating a list of odd numbers
odd_numbers = list(range(1, 11, 2)) # Start from 1 and adds 2

print(numbers)
print(even_numbers)
print(odd_numbers)

output:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[2, 4, 6, 8, 10]
[1, 3, 5, 7, 9]

Here we used the range() and built-in list() function to create a list up to 10, but note here that the list doesn't contain 10 because it'll always run up to n-1. We also created a list of even and odd numbers by specifying the range.

Let's create a list of squares of numbers:

squares = []

for i in range(1, 11):
  square = i**2
  squares.append(square)

print(squares)

output:
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

List comprehension

In the above approach, we create a list of squares by first creating an empty list, then looping to a certain range. In each iteration, the program will find the square of numbers and append it to the list. But if you see, this takes four or five lines of code to create a list of squares. The list comprehension provides the same output with ease in just 1 or 2 lines of code. 

squares = [i**2 for i in range(1, 11)]
print(squares)

output:
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

It is so simple to create a list of squares using list comprehension, here first we write two square brackets, then we raised the power of "i" to 2, after that a for loop inside the brackets which will iterate until the specified range, this process of raising the power of the numbers to 2 and iterating will repeat until 11 and we'll get the output of a list of squares from 1 to 10. 

Slicing a list

Slicing a list is useful in two cases, one is to cut the list into different parts, another is to get a specific part from a list. here is how you can slice through a list.

names = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

print(names[0:3]) # Slice values after 3
print(names[1:4]) # Starts from index 1 to 4
print(names[1:]) # All values except first
print(names[:9]) # All values except last
print(names[-3:]) # slice the values except last three values

output:
[1, 2, 3] [2, 3, 4] [2, 3, 4, 5, 6, 7, 8, 9, 10] [1, 2, 3, 4, 5, 6, 7, 8, 9] [8, 9, 10]

Merging two lists

Merging two lists is really simple, just add all the lists you want to merge using the "+" operator.

list1 = [1,2,3,4]
list2 = [5,6,7,8]
list3 = [9,10,11,12]

print(list1+list2+list3)

output:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]