The world’s leading publication for data science, AI, and ML professionals.

Python Lists from Scratch !!!

Let's understand the Python Lists from basic to advance level.

GangBoard
GangBoard

The list is a data structure in Python which acts as a container to hold or store multiple data at the same time. Lists are mutable or changeable and ordered sequence of elements. To know more about Python Lists you can visit the official Python Lists documentation. One thing you have to keep in mind is that often we must declare lists using [ ] brackets. The elements inside the [ ] are the values of the list. For example:

# Creating an empty list called "list"
list = [ ]
# Adding the values inside the list
list = [ 1, 2, 3, 4, 5]
# Printing the list
list
[1, 2, 3, 4, 5]

Here the name of the list is "list" and the list values are 1, 2, 3, 4, 5. The advantages of lists are the values inside the lists need not be of the same type meaning:

# Adding the values irrespective of their data type: Integer, String, float.
list = [1, 2, 3, "Tanu", 4.0, 4/2]
list
[1, 2, 3, 'Tanu', 4.0, 2.0]

In order to check the variable if it is a list or not, use the "type" method as follows:

# Create a list as list
list = [1, 2, 3, 4, 5]
# Use type method by passing the name of the list as an arguement type(list)
list

1) Creating, accessing and calculating the length of a list.

Let us create a list called "name" and then insert some values, later we can then access the elements inside the list using the index with the help of [ ] by placing the index values inside it. We can then calculate the length of the list by using the len ( ) method, just pass the name of the list as an argument to the len( ) method, finally we can also get the length of the individual elements inside the list by using the same len ( ) method but this time we should specify the index position as an argument.

# Creating a list called name
name = ["Tanu", "Nanda", "Prabhu"]
name
['Tanu', 'Nanda', 'Prabhu']
# Accessing the elements in the list
name[0] # Tanu
'Tanu'
# Calculating the length of the list.
len(name)
3
# Calculating the length of individual elements in a list
len(name[0])   # length of "Tanu" is 4
4

2) Assignment operator on Lists

Assignment with a "=" on lists does not make a copy. Instead, the assignment makes the two variables point to the one list in the memory. Sometimes an assignment operator can be used to copy from one list to the other.

# Creating a list called name
name = ["Tanu", "Nanda", "Prabhu"]
name
['Tanu', 'Nanda', 'Prabhu']
# Creating an empty list names
names = []
names
[]
# Using assignment operator on Lists doesn't create a copy.
names = name
# Assigning the old list name to the new list names.
names
['Tanu', 'Nanda', 'Prabhu']

3) Appending two lists to a single list.

Usually appending two lists can be done by using append( ) method, but appending can also be done by using a ‘+‘ (here + doesn’t mean addition) whereas + can be used to add or merge two lists into a single list as shown below.

# Creating a new list called Cars
cars = ["Mercedes", "BMW", "Audi"]
cars
['Mercedes', 'BMW', 'Audi']
# Creating a new list called bikes
bikes = ["Honda", "Yamaha", "Aprilla"]
bikes
['Honda', 'Yamaha', 'Aprilla']
# Appending both the lists
cars_bikes = cars + bikes
cars_bikes
['Mercedes', 'BMW', 'Audi', 'Honda', 'Yamaha', 'Aprilla']

4) Using FOR and IN in lists

In Python the "for" and "in" are called constructs, these constructs are easy to use, they are used whenever you need to iterate over a list.

# Creating a list
list = [1, 2, 3, 4, 5]
# Assigning sum to 0
sum = 0
# Using a for loop to iterate over the list
for num in list:
  sum = sum + num
print(sum) # 15
15

5) Using IF and IN in lists.

The "if " and "in" construct on its own is an easy way to test if an element appears in a list (or other collection), it tests if the value is in the collection, returning True/False. This also works for the string, characters in Python.

# Creating a list
list = [1, 2, 3, 4, 5]
if 1 in list:
  print("True")
else:
  print("False")
True

6) Range function in Python.

The Range function in Python is used as a boundary in the looping constructs, the range function starts from 0 to n-1, it doesn’t include the last number as shown below.

# Range starts 0 to n-1
for i in range(5):
 print(i)
0 
1 
2
3
4

7) While loop in python

Python has a standard while-loop which works similar to the For loop, first you have to initialize, then insert a condition and finally increment.

# Initialisin i to 0
i = 0 
while i < 10:
 print(i) # 0–9
 i = i+ 1
0
1
2
3
4
5
6
7
8
9

8) List methods.

Below are some of the most common list methods shown with an example.

a) List append method

The list.append( ) just appends an element to the list but never returns anything, it just appends the element to the existing list.

# Creating a new list called list
list = ['Tanu', 'Nanda']
# Before appending
list
['Tanu', 'Nanda']
# Using the append operation on the current ("Prabhu") is the value to be appended.
list.append("Prabhu")
# After appending
list
['Tanu', 'Nanda', 'Prabhu']

b) List insert method

List.insert( ) operation is used to insert the elements inside a list with a specified index position.

# Creating a new list called list
list = ['Tanu', 'Nanda']
# Before inserting
list
['Tanu', 'Nanda']
# Insert Operation on the existing list, here the index position is 2.
list.insert(2, "Prabhu")
# After Inserting
list
['Tanu', 'Nanda', 'Prabhu']

c) List extend method

The extend method adds the elements to the end of the new list. It is similar to append but you have to pass the list as an argument whereas in append it’s not necessarily true.

# Creating a new list called list
list = ['Tanu', 'Nanda']
# Before extending
list
['Tanu', 'Nanda']
# Using extend but make sure that you put the elements in a []
# Without []
list.extend("Prabhu")
# After extending
list
['Tanu', 'Nanda', 'P', 'r', 'a', 'b', 'h', 'u']
# After []
list.extend(["Prabhu"])
list
['Tanu', 'Nanda', 'P', 'r', 'a', 'b', 'h', 'u', 'Prabhu']

d) List index method

The index operation in list searches the element in the list and then returns the index of that element. If the element is not present in the list then the index method returns a value error telling that the element is not in the list.

# Creating a new list called list
list = ['Tanu', 'Nanda']
# Before indexing
list
['Tanu', 'Nanda']
# After indexing, type the element that you want to index.
list.index("Nanda")
1
# If the element is not present then you get an error
list.index("Mercedes")
---------------------------------------------------------------------------
ValueErro Traceback (most recent call last)
<ipython-input-4-4f3441849c1e> in <module>()
----> 1 list.index("Mercedes")
ValueError: 'Mercedes' is not in list

e) List remove method

The Remove method in lists searches for the element and then on matching removes the element present in the list. Also throws an error when the element is not in the list.

# Creating a new list called list
list = ['Tanu', 'Nanda']
# Before removing
list
['Tanu', 'Nanda']
# After removing
list.remove("Nanda")
list
['Tanu']
list.remove('Prabhu')
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-8-9df87da8501a> in <module>()
----> 1 list.remove('Prabhu')
ValueError: list.remove(x): x not in list

f) List sort method

As the name suggests the sort method sort the elements in ascending order. This method doesn’t return anything.

# Creating a list called list
list = [1, 4, 5, 2, 3]
# Before sorting
list
[1, 4, 5, 2, 3]
# After sorting
list.sort()
list
[1, 2, 3, 4, 5]

g) List Reverse method

As the name suggests the reverse method reverses the entire list. This method doesn’t return anything.

# Creating a list called list
list = [1, 2, 3, 4, 5]
# Before Reversing
list
[1, 2, 3, 4, 5]
list.reverse()
# After the reverse
list
[5, 4, 3, 2, 1]

h) List pop method

The Pop method removes and returns the element at the given index. Returns the rightmost element if the index is omitted (roughly the opposite of append( )).

# Creating a list called list
list = [1, 2, 3, 4, 5]
# Before popping
list
[1, 2, 3, 4, 5]
# After popping
list.pop(1)
2
list
[1, 3, 4, 5]

9) List Slices

Slicing the list means cutting down the list elements, it and can also be used to change sub-parts of the list.

list = ['a', 'b', 'c', 'd']
list
['a', 'b', 'c', 'd']
list[1:-1]     ## ['b', 'c']
list
['a', 'b', 'c', 'd']
list[0:2] = 'z'    ## replace ['a', 'b'] with ['z']
list               ## ['z', 'c', 'd']
['z', 'c', 'd']

10) Converting a string to a list

This is the most important technique, often we need to convert the string to a list in our projects, this is an easy approach that does the job for us. This below example was referred from geeksforgeeks.com. Here we are using the split method from the strings where the split method just splits the elements from the string and then broadcasts into a list as shown below.

# Creating a String
String = "Tanu"
String
'Tanu'
# Checking for the type 
type(String)
str
# Using the split method to split the string into a list.
list = list(String.split(" ")) 
list
['Tanu']
type(list)
list

Sometimes when you try to convert the string to a list, then you get an error as shown below, to solve this you just have to change the name of the list to something else, here in the above examples I have taken the name of the list as "list" so this often creates a name collision with the list method, so If you are using Google Colab or Jupyter notebook this error often shows up then you have to restart the kernel and run all the cells again. So the solution is just to change the name of the list and then restart the kernel if you get this error.

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-46-58e364821885> in <module>()
----> 1 list = list(String.split(" "))
      2 list
TypeError: 'list' object is not callable

Hence above are the very important techniques or methods of Lists in Python. Most of the examples were referred from Python Lists from Google. I have written this in a simple way such that everybody can understand and master the concepts of lists in Python. If you guys have some doubts in the code, the comment section is all yours.

ThankYou.


Related Articles