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 "num"
num = [ ]
# Adding the values inside the list
num = [ 1, 2, 3, 4, 5]
# Printing the list
num
[1, 2, 3, 4, 5]
Here the name of the list is "num" 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.
num = [1, 2, 3, "Tanu", 4.0, 4/2]
num
[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 num
num = [1, 2, 3, 4, 5]
# Use type method by passing the name of the list as an arguement
type(num)
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
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']
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']
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
num = [1, 2, 3, 4, 5]
# Assigning sum to 0
sum = 0
# Using a for loop to iterate over the list
for i in num:
sum = sum + i
print(sum) # 15
15
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
num = [1, 2, 3, 4, 5]
if 1 in num:
print("True")
else:
print("False")
True
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
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
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 name
name = ['Tanu', 'Nanda']
# Before appending
name
['Tanu', 'Nanda']
# Using the append operation on the current ("Prabhu") is the value to be appended.
name.append("Prabhu")
# After appending
name
['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
name = ['Tanu', 'Nanda']
# Before inserting
name
['Tanu', 'Nanda']
# Insert Operation on the existing list, here the index position is 2.
name.insert(2, "Prabhu")
# After Inserting
name
['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 name
name = ['Tanu', 'Nanda']
# Before extending
name
['Tanu', 'Nanda']
# Using extend but make sure that you put the elements in a []
# Without []
name.extend("Prabhu")
# After extending
name
['Tanu', 'Nanda', 'P', 'r', 'a', 'b', 'h', 'u']
# After []
name.extend(["Prabhu"])
name
['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 name
name = ['Tanu', 'Nanda']
# Before indexing
name
['Tanu', 'Nanda']
# After indexing, type the element that you want to index.
name.index("Nanda")
1
# If the element is not present then you get an error
name.index("Mercedes")
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-28-e4d303e9b027> in <module>() ----> 1 name.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 name
name = ['Tanu', 'Nanda']
# Before removing
name
['Tanu', 'Nanda']
# After removing
name.remove("Nanda")
name
['Tanu']
name.remove('Prabhu')
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-31-0cd347413bd4> in <module>() ----> 1 name.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 num
num = [1, 4, 5, 2, 3]
# Before sorting
num
[1, 4, 5, 2, 3]
# After sorting
num.sort()
num
[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 num
num = [1, 2, 3, 4, 5]
# Before Reversing
num
[1, 2, 3, 4, 5]
num.reverse()
# After the reverse
num
[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 num
num = [1, 2, 3, 4, 5]
# Before popping
num
[1, 2, 3, 4, 5]
# After popping
num.pop(1)
2
num
[1, 3, 4, 5]
Slicing the list means cutting down the list elements, it and can also be used to change sub-parts of the list.
char = ['a', 'b', 'c', 'd']
char
['a', 'b', 'c', 'd']
char[1:-1] ## ['b', 'c']
char
['a', 'b', 'c', 'd']
char[0:2] = 'z' ## replace ['a', 'b'] with ['z']
char ## ['z', 'c', 'd']
['z', 'c', 'd']
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.
name = list(String.split(" "))
name
['Tanu']
type(name)
list
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.