Python List Tutorial (Create, Access, Slice, Add or Delete Elements to List)

Python List: Explore the ways to Create, Access, Slice, Add/Delete Elements.

Python includes 4 collection data types as mentioned below:

  • List
  • Set
  • Dictionary
  • Tuple

In this tutorial, we will discuss in detail about List and its various operations. In Python, list is a data structure or it is just like an array which is used to store multiple data at once.

If you have experience in any other programming languages like Java, C, C++ etc, then you will be familiar with the concept of arrays. However, list is almost the same as arrays.

Python List

What is Data Structure?

Computers are used to store a huge number of data or to process a huge number of data with high speed and accuracy. Hence, it is best to store data permanently for quick access.

While data processing happens, it should happen within the shortest possible time without losing accuracy. We use the data structure to deal with data in an organized manner and store data in the memory for processing.

As Python is a high-level and interpreted programming language, it is very important to make use of the data structure in Python.

What is List?

A list is a data structure that is used to store multiple data at once.

The data stored in a list is homogeneous and that, in turn, makes it the most powerful feature of list in Python. We can store multiple data of different data types like String, Integers, and objects as well in a single list.

List are mutable in Python, thus data can be altered at any time even after the creation. Lists are very powerful for implementing stacks and queues in Python.

As discussed earlier, list stores data in an ordered sequence and data stored in a list are accessed using their index, and for list, the index will always start from Zero. Each element has a specific place in the list and all of those data are accessed with the help of an index.

In list, we can store the same value multiple times and each data will be considered as a separate and unique element. Lists are best to store data and iterate over them at a later time.

Creating a List

Data in a list are stored with comma-separated and enclosed in a square bracket ([]). Items in the list need not be of the same type.

Syntax:

List = [item1, item2, item3]

Example 1:

List = [ ]

Example 2:

List = [2, 5, 6.7]

Example 3:

List = [2, 5, 6.7, ‘Hi’]

Example 4:

List = [‘Hi’, ‘Python’, ‘Hello’]

In the above examples, we can observe that we have stored items of different data types with comma separated, 2 and 5 are of type Integer, 6.7 is of type float and ‘Hi’ is of type String, all these items are enclosed in a list and that makes it a List.

We can declare an empty list as well. We can also declare list inside another list, and we call this as a nested list.

Example 5:

List = [‘Hi’, [2, 4, 5], [‘Hello’]]

In the above example, you can observe that a list has been declared inside another list.

Accessing Values in List

There are various ways through which we can access the items present inside the list in Python.

With the help of the index, we can access the elements of the list. Index starts from 0 and the index should always be an Integer. If we use an index other than integer like float, then it will result in TypeError.

Example 1:

List = [2, 5, 6.7, ‘Hi’]
print(“List is:”, List)

Output:

List is: [2, 5, 6.7, ‘Hi’]

Accessing_values_in_list_example_1

Output:

Accessing_values_in_list_example_1_output

In the above example, we are directly printing the list using the print function, we are not accessing the individual element from the list.

Let’s access the individual element from the list.

Example: 2

List = [2, 5, 6.7, ‘Hi’]
print(“Second element of the list is:”, List[1])

Output:

Second element of the list is: 5

Accessing_values_in_list_example_2

Output:

Accessing_values_in_list_example_2_output

In the above example, you can observe that we are printing the second element of the list that is 5, but you may a get a question as for why in the print statement we are printing List[1]? That is because the index starts from Zero, hence List[1] refers to the second element of the list.

Example: 3

List = [2, 5, 6.7, ‘Hi’]
print(“First element in the List is: ”, List[0])
print(“Last element in the List is: ”, List[3])

Output:

First element in the List is: 2
Last element in the List is: Hi

Accessing_values_in_list_example_3

Output:

Accessing_values_in_list_example_3_output

Example: 4

List = [‘Hi’, [2, 4, 5]]
print(“First element of the list is: ”, List[0][1])
print(“Elements present inside another list is: ”, List[1][2])

Output:

First element of the list is: i
Elements present inside another list is: 5

Accessing_values_in_list_example_4

Output:

Accessing_values_in_list_example_4_output

In the above program, if you observe carefully, you can see that we are accessing the elements from the nested list.

Internally the data will be stored in a matrix format as shown below:

Hi

2 4 5

Hence, when we try to access List[0][1] then it will point to 1st row and 2nd column, thereby data will be ‘i’.

Similarly, when we try to access List[1][2] then it will point to 2nd row and 3rd column, thereby, data will be 5.

Negative Indexing

We can access data using a negative index as well. A negative index will always start from -1 and -1 refers to the last element and -2 refers to the last second item and so on.

Example: 1

List = [2, 5, 7, 3]
print(“Last element in the list is: ”, List[-1])

Output:

Last element in the list is: 3

Negative_indexing_example_1.1

Output:

Negative_indexing_example_1_output1

Example: 2

List = [2, 5, 7, 3]
print(“Second element in the list is: ”, List[-3])

Output:

Second element in the list is: 5

Negative_indexing_example_2.1

Output:

Negative_indexing_example_2_output1

Slicing the List

Using the slice operator (:) we can access a range of elements from the list

Example: 1

List = [1, 2, 3, 4, 5, 6, 7]
print(“Elements from 2nd to 5th is: ”, List[1:5]) 
print(“Elements beginning to 2rd is: ”, List[:-3])
print(“Elements 4th to end is: ”, List[3:])
print(“Elements from start to end is: “, List[:])

Output:

Elements from 2nd to 5th is: [2, 3, 4, 5]
Elements beginning to 2rd is: [1, 2, 3, 4]
Elements 4th to end is: [4, 5, 6, 7]
Elements from start to end is: [1, 2, 3, 4, 5, 6, 7]

Slicing_list_example_1.1

Output:

Slicing_list_example_1_output1

We can also access the elements present inside the list using for loop.

Example: 2

List = [1, 2, 3, 4, 5, 6, 7]
forele in List:
     print(ele)

Output:

1
2
3
4
5
6
7

Slicing_list_example_2

Output:

Slicing_list_example_2_output1

Remember the indexing format below:

HELLO5794
012345678
-9-8-7-6-5-4-3-2-1

As discussed earlier, List in python is mutable, which means the elements can be changed even if it is an Integer or String or any datatype.

We can update the list using the assignment operator.

Example: 3

List = [2, 4, 6, 9]
#updating the first element
List[0] = 7
print(“Updated list is: ”, List)

Output:

Updated list is: [7, 4, 6, 9]

Slicing_list_example_3.1

Output:

Slicing_list_example_3_output1

In the above example, we are updating the first element of the list ‘2’ with a new element ‘7’.

Example: 4

List = [2, 5, 1, 3, 6, 9, 7]
#updating one or more elements of the list at once
List[2:6] = [2, 4, 9, 0]
print(“Updated List is: ”, List)

Output:

Updated List is: [2, 5, 2, 4, 9, 0, 7]

In the above example, we are updating the list of data into the list.

Slicing_list_example_4.1

Output:

Slicing_list_example_4_output1

Adding Elements to the List

There are several ways in which we can add elements to the list, and python has an in-built function called append().

Using append(), we can add only one element to the list, if you want to add multiple elements to the list then we have to make use of for loop. append() function always adds the element at the end of the list, append() function takes only one argument.

If you want to add elements at a specific position then you just need to use the insert() method. insert() takes two arguments i.e. position and value, position refers to the index, where the elements need to be added and value refers to the element to be added to the list.

There is one more method called extend(), using which we can add elements to the list. extend() method is used to add a list of elements to the list. Similar to append() method and extend() method, it will also add elements at the end of the list.

Example: 1

List = [“Hello”, “Good Morning”]
print(“List before appending values is: “, List)
List.append(“Python”)
List.append(“Hi”)
print(“List after appending values is: ”, List)

Output:

List before appending values is: [“Hello”, “Good Morning”]
List after appending values is: [“Hello”, “Good Morning”, “Python”, “Hi”]

In the above example, we are appending ‘Python’ and ‘Hi’ values to the end of the List.

append() in python

Output:

append() in Python Output

Example: 2

List = [“Hello”, “Good Morning”]
print(“List before appending values is: “, List)
print(“Length of the list before appending is: “, len(List))
List.append(“Python”)
List.append(“Hi”)
print(“List after appending values is: ”, List)
print(“Length of the list after appending is: “, len(List))

Output:

List before appending values is: [“Hello”, “Good Morning”]
Length of the list before appending is: 2
List after appending values is: [“Hello”, “Good Morning”, “Python”, “Hi”]
Length of the list after appending is: 4

We can find the length of the list using the len() function, as shown in the above example.

Adding_element_to_the_list_example_2

Output:

Adding_element_to_the_list_example_2_output

We can also add multiple values to the list using for loop.

Example: 3

List = [7, 9, 8]
print(“List before adding elements is: “, List)
print(“Length of List before adding elements is: “, len(List))
for i in range(2, 6):
    List.append(i)
print(“List after adding elements is: “, List)
print(“Length of List after adding elements is: “, len(List))

Output:

List before adding elements is: [7, 9, 8]
Length of List before adding elements is: 3
List after adding elements is: [7, 9, 8, 2, 3, 4, 5]
Length of List after adding elements is: 7

Adding_element_to_the_list_example_3

Output:

Adding_element_to_the_list_example_3_output1

What happens if we append a list of list to a list? Let’s see that in the below example.

Example: 4

List1 = [“Hi”, “Python”]
List2 = [1, 5, 7, 2]
List1.append(List2)
print(“List1 after appending List2 is: “, List1)

Output:

List1 after appending List2 is: [“Hi”, “Python”, [1, 5, 7, 2]]

If you notice in the above example, when we append List2 to List1 then List1 will become a nested list.

Adding_element_to_the_list_example_4

Output:

Adding_element_to_the_list_example_4_output

If you don’t want to make the list as a nested list after appending the list, then it’s better to use the extend() method.

Example: 5

List1 = [“Hi”, “Python”]
List2 = [1, 5, 7, 2]
List1.extend(List2)
print(“List1 after appending List2 is: “, List1)

Output:

List1 after appending List2 is: [“Hi”, “Python”, 1, 5, 7, 2]

When we use extend() method, the elements of List1 will be extended with the elements of List2. Remember it will not append the list when we use the extend() method.

Adding_element_to_the_list_example_5

Output:

Adding_element_to_the_list_example_5_output

When you extend a list with a string, then it will append each character of the string to the list, as a string is iterable.

Example: 6

List = [1, 5, 7, 2]
List.extend(“Python”)
print(“List after extending the String is: “, List)

Output:

List after extending the String is: [1, 5, 7, 2, ‘P’, ‘y’, ‘t’, ‘h’, ‘o’, ‘n’]

Adding_element_to_the_list_example_6

Output:

Adding_element_to_the_list_example_6_output

List append() vs extend()

Let’s take a look at some examples for extend() and append().

Example: 1

def my_fun():
    List1 = [“Hi”, 1, “Hello”, 2, 5]
    print(“The elements of List is: “, List)
    List.append(“Python”)
    print(“List after appending the String is: “, List)
    List.append([“one”, “two”, 3])
    print(“List after appending the list is: “, List)
    List2 = [“Apple”, “Orange”, 2, 8]
    List1.extend(List2)
    print(“List1 after extending the List2 is: “, List1)


if __name__ == “__main__”:
    my_fun()

Output:

The elements of List is: [“Hi”, 1, “Hello”, 2, 5]
List after appending the String is: [“Hi”, 1, “Hello”, 2, 5, “Python”]
List after appending the list is: [“Hi”, 1, “Hello”, 2, 5, “Python”, [“one”, “two”, 3]]
List1 after extending the List2 is: [“Hi”, 1, “Hello”, 2, 5, “Python”, [“one”, “two”, 3], “Apple”, “Orange”, 2, 8]

List_append_vs_extend_example_1.1

Output:

List_append_vs_extend_example_3_output1

Example: 2

List = [“Apple”, “Orange”, “Mango”, “Strawberry”]
print(“List before inserting is: “, List)
List.insert(2, “Watermelon”)
print(“List after inserting is: “, List)

Output:

List before inserting is: [“Apple”, “Orange”, “Mango”, “Strawberry”]
List after inserting is: [“Apple”, “Orange”, “Watermelon”, “Mango”, “Strawberry”]

List_append_vs_extend_example_2.1

Output

List_append_vs_extend_example_2_output1

As we discussed earlier, insert() method is used to insert values at a specific index of the list.

Example: 3

List1 = [2, 4, 6, 8]
print(“List after adding the elements is: “, List1 + [1, 3, 5, 7])
print(“After adding same elements repeatedly is: “, [“Hi”] *5)

Output:

List after adding the elements is: [2, 4, 6, 8, 1, 3, 5, 7]
After adding the same elements repeatedly is: [‘Hi’, ‘Hi’, ‘Hi’, ‘Hi’, ‘Hi’]

List_append_vs_extend_example_3.1

Output:

List_append_vs_extend_example_3_output1

Deleting or Removing Elements from a List

We can also delete or remove elements from the list using del and remove() statements.

Let’s see in the below example.

Example: 1

List = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(“List before deleting 3rd element is: ”, List)
del List[3]
print(“List after deleting 3rd element is: ”, List)
del List[1:3]
print(“List after deleting multiple elements is: “, List)

Output:

List before deleting 3rd element is: [1, 2, 3, 4, 5, 6, 7, 8, 9]
List after deleting 3rd element is: [1, 2, 3, 5, 6, 7, 8, 9]
List after deleting multiple elements is: [1, 5, 6, 7, 8, 9]

In the above example, you can observe that we have used del statement to delete an element or multiple statements from the list.

Deleting_or_removing_element_from_the_list_example_11

Output:

Deleting_or_removing_element_from_the_list_example_1_output1

Now we will see about the remove() method.

Example: 2

List = [1, 2, 3, 4, 5, 6, 7]
print(“List before removing a element is: “, List)
List.remove(3)
print(“List after removing a element is: “, List)
List.pop()
print(“List after poping the element is: “, List)

Output:

List before removing an element is: [1, 2, 3, 4, 5, 6, 7]
List after removing an element is: [1, 2, 4, 5, 6, 7]
List after popping the element is: [1, 2, 4, 5, 6]

In the above example, you can observe that we are removing an element from the list using remove() method. The pop() method is used to remove/delete the last element from the list.

Deleting_or_removing_element_from_the_list_example_2.1

Output:

Deleting_or_removing_element_from_the_list_example_2_output1

List Methods

MethodsDescription
clear()To remove all the elements from the list.
append()To add element at the end of the list.
insert()To insert element at a specific index of the list.
extend()To add list of elements at the end of the list.
count()To return number of elements with a specific value.
index()To return the index of the first element.
pop()To delete/remove the element from the last in a list.
reverse()To reverse an existing list.
remove()To remove the elements from the list.

Conclusion

This tutorial on the Python list can be concluded with the following Pointers:

  • List is one of the datatypes in Python, which is also referred to as data structure.
  • List is used for storing a large number of values of any datatypes in one single variable, which in turn helps to access easily.
  • Index for list always starts from zero like the other programming languages.
  • If you are working on list, then you must remember all the common in-built functions of it.

Happy Reading!!