Python List

In this tutorial, we will learn about python list and how to use their methods.

Python List

What is Python List?

The python list is used to store an ordered sequence of values in a single variable, or we can say the list is the collection of the items of different data types. It is a very flexible data type in Python. The list is like an array from the other programming language.

The list is mutable so that we can change the value in the list at any time.

How to Create a List in Python?

As a list is a collection of the items, we need to separate all the values with a comma (,), and it should be enclosed in square brackets [ ].

Example: how to print a list in python

mylist= [1,2,3,4]
print(mylist)

Output:

[1, 2, 3, 4]

We can add any value in the list, but if it is a string, it should be in a single quote (‘) or double quote (“).

Example:

mylist = [1,‘two’, 3.5, ‘four’]
print(mylist)

Output:

[1, ‘two’, 3.5, ‘four’]

Example:

mylist = [1,‘two’, 3.5, ‘four’]
print(type(mylist))

Output:

<class ‘list’=“”></class>

How to Create a Nested list in Python?

As we have learned about the nested loop and nested condition also known as the list of lists in python, the nested list is slightly different as loops and conditions are functions; a list is a data type or a data structure.

Let see a simple example of a python nested list by creating one.

Example of python list of lists.

X = [1,2,[3,4,5],6,7,8,[9,10]]
print(X)

Output:

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

Example of the nested list with multiple data types

X = [1,“Two”,[3,‘Four’,5],“Six”,7,8,[9.5,10]]
print(X)

When we execute this program, we will get follow output

[1, ‘Two’, [3, ‘Four’, 5], ‘Six’, 7, 8, [9.5, 10]]

How to access elements from a list?

There are various ways to access elements or values from a list. Here we will learn about accessing elements using Positive and negative indexes.

It is the same way we have learned in our previous tutorial on a python string.

As we already have learned about indexing in python, and as it starts from 0, we can see a list as a sequence of elements, and we can index them as shown in the image.

List Index

Positive indexing in Python list

As we can see in the above image list index starts from 0, we can access an item in a list using the [ ] operator. So here, our list has 6 elements, and we have an index from 0 to 5.

The index must be an integer. We can’t use float or other types; this will result in TypeError.

Let check an example on how to access elements on the list.

my_list = [‘p’,‘y’,‘t’,‘h’,‘o’,‘n’]
print(my_list[2])
print(my_list[0])
print(my_list[5])

The output will be:

t
p
n

Let learn how to access elements in the nested list.

How to access elements in the nested list?

nested_list = [‘We’,‘are’,‘using’,[‘Python’,3.8]]
print(nested_list[1])
print(nested_list[3][1])
print(nested_list[2][1])

Output:

are
3.8
s

We can’t use a string or a float as an index in the list.

nested_list = [‘We’,‘are’,‘using’,[‘Python’,3.8]]
print(nested_list[3.5])

Output:

Traceback (most recent call last):
File “nested_list.py”, line 4, in <module>
print(nested_list[3.5])
TypeError: list indices must be integers or slices, not float</module>

As we can see, it is troughing an error because we can’t use a float as an element in the list.

Negative Indexing in Python list

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.

my_list = [‘p’,‘y’,‘t’,‘h’,‘o’,‘n’]
print(my_list[-4])
print(my_list[-6])

The output of the negative indexing program will be.

t
p

Slicing of the list in Python

We can slice certain elements from a list.

How to slice a list in python?

We have learned about accessing an element in the previous tutorial now, in the same way using square brackets [ ] we can slice a list by adding colon: between two indexes.

Let see how we can slice a list.

Example of slicing a list.

my_list = [‘p’,‘y’,‘t’,‘h’,‘o’,‘n’]
print(my_list[2:5])
print(my_list[:-4])
print(my_list[2:])
print(my_list[:])

And the output will be 

[‘t’, ‘h’, ‘o’]
[‘p’, ‘y’]
[‘t’, ‘h’, ‘o’, ‘n’]
[‘p’, ‘y’, ‘t’, ‘h’, ‘o’, ‘n’]

Concatenation of Python Lists

Concatenation of python list means to add or merge two or more lists into one list, not like a nested list.

How to Concatenated python lists?

We can concatenate the python list using two ways.

  1. Using + operator
  2. Using extend() method

Let us check the first method to merge two lists using an example.

Example of the concatenation of python list using + operator

List_1 = [1,2,3,4]
List_2 = [5,6,7,8]
List_3 = List_1 + List_2
print(List_1)
print(List_2)
print(List_3)

When we run this program, we will get this result.

Output:

[1, 2, 3, 4]
[5, 6, 7, 8]
[1, 2, 3, 4, 5, 6, 7, 8]

Using extend() method:

extend() operator can be used to concatenate one list into another. It is not possible to store the value in the third list. One of the existing lists has to store the concatenated result.

Example of extend() method to concatenate python list.

List_1 = [1,2,3,4]
List_2 = [5,6,7,8]
List_3 = List_1.extend(List_2)
print(List_3)
print(List_1)

The output of the above program will be as follow.

Output:

None
[1, 2, 3, 4, 5, 6, 7, 8]

As we can see first, we are storing the result of extend() the method to List_3, but it gives us None as an output because we cannot store the result of extend()  method to another string. We can only merge one list with another list as we can see in the program List_2 has been merged with List_1.

Multiplication of List

We can multiple elements in the list using the * operator.

Check the example here.

Example of multiplication in list

my_list = [‘p’,‘y’,‘t’,‘h’,‘o’,‘n’]
print(my_list * 3)

Output:

[‘p’, ‘y’, ‘t’, ‘h’, ‘o’, ‘n’, ‘p’, ‘y’, ‘t’, ‘h’, ‘o’, ‘n’, ‘p’, ‘y’, ‘t’, ‘h’, ‘o’, ‘n’]

As we can see, the list has multiplied itself 3 times based on our code.

We can also use multiple operators in the list element. Let’s check it with an example.

Example:

my_list = [‘p’,‘y’,‘t’,‘h’,‘o’,‘n’]
print(my_list[3] * 2)

Output:

hh

How to change or add elements to a list?

As lists are mutable, that means we can change their elements, unlike string or tuple.

There are multiple ways to change or add an element to the list, as follows.

  1. Using + operator
  2. Using append() method
  3. Using inset() method
  4. Using extend() method

Using + Operator

We can use the assignment operator equal ( = ) to change an item or a range of items, but we can’t use = to add or declare new elements in the list just like we do to declare a variable or other functions.

Check the example here.

my_list = [5,4,7,8]
my_list[2] = 0
print(my_list)

Output:

[5, 4, 0, 8]

Here we have changed the value of index 2, which is 7 to 0 with = operator.

Using append() Method

The append() method in python is used to append or add an element to the end of the list; we can not add elements at the starting of the list or in between.

Syntax:

list.append(element)

Let understand the append method using an example.

Example of append method in a python list.

a = [“apple”, “banana”, “cherry”]
b = “Ford”
print(“List before using append method.”)
print(a)
a.append(b)
print(“List after using append method.”)
print(a)

When we execute this program, we will get the following result.

The output of the append() method in the list is as below.

List before using the append method.
[‘apple’, ‘banana’, ‘cherry’]
List after using the append method.
[‘apple’, ‘banana’, ‘cherry’, ‘Ford’]

Using insert() method

The insert() method in python is used to insert an element in the specified index; unlike the append() method, we can easily insert an element to the given index.

The syntax of the insert() method is

list.insert(indx, elem)

Here, elem is the value we want to add to a list, and index is the index we want to add the element. Please note that all the elements after the new element we inserted will be shifted to the right.

The insert() method does not return anything. It returns None. As a result, it only updates the given element in the current list.

Let us understand the insert() method using an example.

Example of insert method in a list.

# vowel list
vowel = [‘a’, ‘e’, ‘i’, ‘u’]
# ‘o’ is inserted at index 3
# the position of ‘o’ will be 4th
vowel.insert(3, ‘o’)
print(‘Updated List:’, vowel)

The output will be as follow.

Updated List: [‘a’, ‘e’, ‘i’, ‘o’, ‘u’]

Using extend() method

Extend method can be learned in the Concatenated python lists section. (Link)

Deleting an element in the python list

Hance python list is mutable. Just like changing and appending an element, we can also delete an element in the python list.

How to delete an element in the Python list?

We can delete an element using the following method:

  1. del function
  2. remove() method
  3. pop() method

Using del function

Using the del function, we can delete or remove elements from a list.

Syntax of del function is:

del list[element]

Let see an example of how to delete an element using the del method.

my_list = [1,2,3,4,5]
print(my_list)
del my_list[3]
print(my_list)

When we run this program, we will get the following result.

Output:

[1, 2, 3, 4, 5]
[1, 2, 3, 5]

We can also delete multiple elements in sequence using the del method by adding colon: between two index elements.

Example to delete multiple elements in sequence using del method

my_list = [1,2,3,4,5]
print(my_list)
del my_list[2:4]
print(my_list)

Output will be:

[1, 2, 3, 4, 5]
[1, 2, 5]

Our program has deleted the two items from the list based on our code, as we can see from the output.

Using remove() method

The remove() method in the python list is used to remove the first matched element with a specific value from the python list.

The Syntax of remove() method will be:

list.remove(element)

Here we can see we are just elements in the parameters, not any index; this is the beauty of the remove() method that we can directly delete an element just string or number.

Let see an example of the remove() method.

Example to remove elements from the list.

cars = [‘Toyota’,‘Volkswagen’,‘BMW’,‘Honda’,‘Ford’]
print(“List is :”,cars)
cars.remove(‘Honda’)
print(“Updated cars list: “, cars)

Output:

List is : [‘Toyota’, ‘Volkswagen’, ‘BMW’, ‘Honda’, ‘Ford’]
Updated cars list: [‘Toyota’, ‘Volkswagen’, ‘BMW’, ‘Ford’]

Example of using remove() method on a list having duplicate elements.

cars = [‘BMW’,‘Toyota’,‘Volkswagen’,‘BMW’,‘Honda’,‘Ford’]
print(“List is :”,cars)
cars.remove(‘BMW’)
print(“Updated cars list: “, cars)

The output will be as follow.

List is : [‘BMW’, ‘Toyota’, ‘Volkswagen’, ‘BMW’, ‘Honda’, ‘Ford’]
Updated cars list: [‘Toyota’, ‘Volkswagen’, ‘BMW’, ‘Honda’, ‘Ford’]

Using pop() method

The pop() method in the python list is used to remove the item based on the index from the list, and this method also returns an output.

The syntax of the pop() method is:

list.pop(index)

Pop() parameters take a single argument, and by default, it takes an index as -1 in the list.

Let see an example of the pop() method.

# programming languages list
languages = [‘Python’, ‘Java’, ‘C++’, ‘French’, ‘C’]
# remove and return the 4th item
return_value = languages.pop(3)
print(‘Return Value:’, return_value)
# Updated List
print(‘Updated List:’, languages)

Output:

Return Value: French
Updated List: [‘Python’, ‘Java’, ‘C++’, ‘C’]

Let see how we can calculate the elements in a list.

How to calculate elements in a list?

We can calculate the length of a list using the len() method.

# programming languages list
languages = [‘Python’, ‘Java’, ‘C++’, ‘French’, ‘C’]
print(len(languages))

The output will be as follow:

5

Membership Test in Python List

The membership test is used to find that whether the specific element is present in a list or not.

We can do a membership test using whether a conditional statement and also within a keyword to find a specific element is present in a list or not.

Let us check an example:

Example of membership test in python list using if conditional statement:

# programming languages list
languages = [‘Python’, ‘Java’, ‘C++’, ‘French’, ‘C’]
if ‘C++’ in languages:
print(“Yes, it is present.”)

The output will be as follow:

Yes, it is present.

We can also do a membership test without any conditional statement just by using a keyword here.

Example:

# programming languages list
languages = [‘Python’, ‘Java’, ‘C++’, ‘French’, ‘C’]
print(“Java” in languages)

The output will be as follows:

True

Here we are checking whether the given condition is true or false, that is why we are getting output with boolean value True.

Python has a set of built-in methods that you can use on lists.

Method Description
append() Adds an element at the end of the list
clear() Removes all the elements from the list
copy() Returns a copy of the list
count() Returns the number of elements with the specified value
extend() Add the elements of a list (or any iterable) to the end of the current list
index() Returns the index of the first element with the specified value
insert() Adds an element at the specified position
pop() Removes the element at the specified position
remove() Removes the item with the specified value
reverse() Reverses the order of the list
sort() Sorts the list