Python List – Create, Access, Slice, Add or Delete Elements

In this Python List tutorial, we will explore ways to Create, Access, Slice, Add/Delete Elements to Python Lists that are arguably one of the most useful data types:

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.

=> Explore The Python Training Series Here

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

Python Lists

What Are Python Lists

In Python, a list is a data type, that stores a collection of different objects (items) within a square bracket([]). Each item in a list is separated by a comma(,) with the first item at index 0.

Note: Moving forward, all the examples in this tutorial will directly run from a Python shell, unless otherwise stated.

Below is an example of a list with 5 items.

>>> l = ['what','who','where','when','how']
>>>l
['what','who','where','when','how']

In the above example, we can see that the list has String objects as items, and each item is separated by a comma.

Characteristics Of Python List

Before we look at how we can manipulate items in a list, let’s look at some of the characteristics that make Python lists favored.

Python Lists Are Container Sequences

Unlike flat sequences(string, array.array, memoryview, etc) that can only hold items of one type, a list is a container sequence that can hold items of one type as well as of different types.

Example with items of one type

Let’s open our python shell and define a list of numbers.

>>> numbers = ['one','two','three','four','five']
>>> numbers
['one','two','three','four','five']

The example above shows a list of items of the same type, in this case of type string(str).

Example with items of different types

Let’s open our Python shell and define another version of a list of numbers.

>>> numbers = ['one',2,3,'four',5.0]
>>> numbers
['one',2,3,'four',5.0]

The example above shows a list of items of different types. The types are string, integer, and float.

// a sketch showing the list of items and their types as annotation

The Python list can also hold all objects such as functions, classes, modules, lists, tuples, and much more.

Open an editor and paste the below code:

def test():
    """This is a function"""
    print("This is a test")

if __name__ == '__main__': 
    print(test)
    # return instance object of function 'test'
    instance = type(test)
    print(instance)
    # create a list of colors
    colors = ["red","blue","green"]
    print(colors)
    
    # create a list holding all the various data types defined above, including boolean.
    my_list = [test, instance, colors, False]
    print(my_list)

Output

Python lists are container sequences

Python Lists Are Ordered Sequences

A Python list is an ordered collection of objects. The position of each item in a list is very important. In fact, two lists with the same items are not the same if the order in which the items are positioned is not the same.

>>> ['a','b','c','d'] == ['a','c','b','d']
False

This characteristic of the Python list makes it possible to access its items by index and slicing(more on this later).

Python Lists Are Mutable Sequences

Python lists are mutable. But what is a mutable object? It’s simply an object that can be modified after it is created. Examples of other mutable sequences are dictionary, array.array, collections.deque.

Why mutable? Sequences like lists are used for complex operations, so it makes sense that they should be able to change, grow, shrink, update, etc. This is only possible with mutability. Mutability also enables us to modify lists in place(more on this).

Let’s verify the mutability of a list with the example below.

Just open an editor and paste the code:

def veryfiy_mutability():
    # create a list
    l = [9,0,4,3,5]

    print("Display before modifying")
    print("List: {}\nId: {}".format(l,id(l)))

    # modify the list by replacing the item at 
    # index 3 to the item -2.
    l[3] = -2

    print("Display after modifying")
    print("List: {}\nId: {}".format(l,id(l)))


if __name__ == '__main__':
    veryfiy_mutability()

Output

Python Lists Are Mutable Sequences

From the above output, we notice that the list before and after modification is different. However, the Id value is the same. The Id value here represents the object’s address in memory – that is obtained with Python id().

This tells us that, though the list content has changed, it is still the same object. Hence, this satisfies our definition: “It’s simply an object that can be modified after it is created

Note: In the example above, we used indexing(more on this) to modify the list.

Manipulating Python Lists

With Python lists, the sky’s our limit. There are countless things we can do with lists like adding, deleting, indexing, slicing, checking for membership, and much more. Also, Python has built-in functions that help to make manipulating lists more exciting.

In this section, we will be looking at some commonly used list operations.

Creating A List

To create a list, you simply put a number of items or expressions in a square bracket separated by commas.

 [expression1, expression2,...,expresionN]
>>> l = [4,3,5,9+3,False]
>>> l
[4, 3, 5, 12, False]

Also, Python has a built-in object called list() that can be used to create lists.

 list( sequence )
>>> l = list() # create an empty list
>>> l
[]

Python list() can take in sequence types and convert them into lists. This is the typical way of converting a tuple into a list.

>>> t = (4,3,5) # tuple
>>>l = list(t) # convert into list
[4,3,5] 

In the example above, we used the data type Tuple. It is similar to a list but unlike lists, it is immutable and its items are enclosed in parentheses.

Another means by which we can create a list is by using list comprehensions that has the following syntax.

 [expression for item in sequence]
>>> [i**2 for i in range(4)]
[0, 1, 4, 9]

It is worth noting that Python lists are passed by reference. Meaning, assigning a list will provide its memory location identity. The mistake that many newbies do is to create lists this way.

>>> l1 = l2 = [4,3] # wrong way to create separate list objects
>>> l1
[4,3]
>>> l2
[4,3]

Here, we might think that we have created two different lists, but truly we have just created one. Let’s demonstrate this by modifying one of the variables.

>>> l1[0] = 0
>>> l1
[0,3]
>>> l2
[0,3]

We notice that modifying one variable changes the other. This is because both the variables l1 and l2 hold the same memory location identity, so they both point to the same object.

Adding Items To A List

Python has many ways to add elements to its list. The most common way is by using the append() method. The other ways are by using the extend() method. Indexing and slicing(more on these later) are more likely used to replace items in a list.

#1) Using append() method

This method takes in a single item and adds it to the end of the list. It doesn’t return a new list but just modifies the list in place(thanks to its mutability).

>>>l = list() # create empty list
>>> l
[]
>>> l.append(4) # add an integer
>>> l
[4]
>>> l.append([0,1]) # add a list
>>> l
[4, [0, 1]]
>>> l.append(4 < 2) # add the result of an expression
>>> l
[4, [0, 1], True]
>>> l.append(x for x in range(3)) # add result of a tuple comprehension
>>> l
[4, [0, 1], True, <generator object <genexpr> at 0x7f71fdaa9360>]

Few things to note from the example above:

  • Items here can be expressions, data types, sequences, and many more.
  • The append() method has a time complexity of (0)1. Meaning it is constant.

#2) Using extend() method

This method takes in an iterable as its argument and adds all the items from it to the end of the list. This method is mostly used when we want to add individual items of a sequence into a list

Basically, the extend() method iterates over its argument and appends each item to the list. Just like the append() method, it doesn’t return a new list but modifies the list in place.

>>> l1 = [3,2,5] # create a list of items
>>> l1
[3, 2, 5]
>>> l2 = [0,0,-1] # create a second list of items
>>> l2
[0, 0, -1]
>>> str = "hello" # create a string(iterable)
>>> str
'hello'
>>> l1.extend(l2) # append all items from l2 to l1
>>> l1
[3, 2, 5, 0, 0, -1]
>>> l1.extend(str) # append all items from str to l1
>>> l1
[3, 2, 5, 0, 0, -1, 'h', 'e', 'l', 'l', 'o']

Few things to note from the above example:

  • A string is iterable, so our extend() method will iterate over its characters.
  • The extend() method has a time complexity of (0)K where K is the length of its argument.

Accessing Items From A List

Indexing and slicing are the most common means that are used to access lists. We can also access items in a list with loops like the for loop.

#1) Indexing

A Python list uses the zero-based numbering system. Meaning, all its items are uniquely identified by an index number starting from 0 to n-1 where n is the length of the list.

Consider the list below:

>>> colors = ['red','blue','green','yellow','black'] # create list
>>> colors
['red','blue','green','yellow','black']
>>> len(colors) # get list length
5

The table below shows their respective indices in the zero-based numbering of a list.

Itemredbluegreenyellowblack
Index01234

From the table above, we see that the first item(‘red’) is at the index position 0 and the last item(‘black’ ) is at index position 4(n-1) where n=5(length of the object colors).

As we saw in the characteristic section above, Python lists are ordered sequences. This allows us to use indexing to access and manipulate its item easily.

Let’s use indexing to access items at particular indices of the colors object created above.

>>> colors  # original list
['red','blue','green','yellow','black']
>>> colors[0]  # access item at index 0
'red'
>>> colors[4]  # access item at index 4
'black'
>>> colors[9]  # access item at index 9

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range

Note: The last statement above is trying to access an item at index position 9 from a list object of length 5. In Python list, accessing an item at an index that doesn’t exist will raise the IndexError exception.

An important concept of indexing is that we can use negative indexing i.e. we can access items of a list in a reversed manner starting at -1 for the last item and ending at -n for the last item where n is the list object’s length.

In the above table, if we use negative indexing, it will look as shown below:

Itemredbluegreenyellowblack
Index-5-4-3-2-1

Let’s use negative indexing to access some items of the color object created above.

>>> colors  # original list
['red','blue','green','yellow','black']
>>> colors[-1]  # access item and index -1(first item counting backward)
'black' 
>>> colors[-3]  # access item at index -3(third item counting backward)
'green'
>>> colors[-5] # access item at index -5 (last item counting backward)
'red'

#2) Slicing

Unlike indexing that only returns one item, slicing on the other hand can return a range of items.

It has the following syntax:

L[n:m]

When n is the index number where the slice starts(defaults to 0), and m is the exclusive index number where the slice ends(defaults to length-1). They are separated by a colon(:)

Consider the below example that uses slicing to access items at particular indices of the colors object created above.

>>> colors  # original list
['red','blue','green','yellow','black']
>>> colors[0:2]               # get first two items
['red', 'blue']
>>> colors[1:4]               # get items at index 1,2 and 3
['blue', 'green', 'yellow']
>>> colors[2:len(colors]      # get items from index 2 to the last item
['green', 'yellow', 'black']  
>>> colors[3:4]               # get one item at index 3. Same as colors[3]
['yellow']
>>>

In the syntax L[n:m], n defaults to 0, and m defaults to the length of the list. So, in examples 1 and 3 above, we could omit n and m as colors[:2] and colors[2:] respectively. Or [:] which in this case returns a shallow copy of the entire list object.

We can also use negative index numbers while slicing lists. This is typically used when we want to access the list in a reversed manner.

>>> colors  # original list
['red','blue','green','yellow','black']
>>> colors[-3:-2]
['green']
>>> colors[-2:]
['yellow', 'black']

Also, there is a third parameter that slicing supports called step(s). It defines how many items to move forward after the first item is retrieved from the list. It defaults to 1.

L[n:m:s]

Using our same color list defined above, let’s use the slice’s third parameter to move 2 steps.

>>> colors  # original list
['red','blue','green','yellow','black']
>>> colors[0:3:2]
['red', 'green']

#3) Using loops

Loops are mostly used to access items in a list in order to manipulate the items. So, in case we want to operate on the items of a list, we can use the for loop to access the items and pass them over to be operated on.

Say, we want to count the number of letters for each item. We can use the for loop to accomplish that.

Open an editor and paste the code below:

def count_letters(l):
    count = {}  # define a dict to hold our count
    for i in l: # loop through the list
        count[i] = len(i)  # for each item, compute its length and store it in the dict
    return count # return the count

if __name__ == '__main__':
    colors = ['red', 'blue', 'green', 'yellow', 'black']
    print(count_letters(colors))

Output

Using loops

To end this section, let’s look at two cool stuff that can be done with slicing.

  • Make a shallow copy of a list

The is the basic way to use the copy() method of the list object or the built-in function copy.copy. However, this can be achieved by slicing.

>>> colors  # original list
['red','blue','green','yellow','black']
>>> colors_copy = colors[:]    # make a shallow copy
>>> colors_copy
['red', 'blue', 'green', 'yellow', 'black']
>>> colors_copy[0] = 0  # modify item at index 0 by changing its value to 0
>>> colors_copy                  # the copied version now has 0 at index 0
[0, 'blue', 'green', 'yellow', 'black']
>>> colors                       # the original version is unchanged
['red', 'blue', 'green', 'yellow', 'black']
>>> 
  • Reverse a list

The basic way is to use the reverse method of the list object or the built-in function reversed(). However, this can be achieved by slicing.

>>> colors        # original list object
['red', 'blue', 'green', 'yellow', 'black']
>>> colors[::-1] # returns a reversed shallow copy of the the original list
['black', 'yellow', 'green', 'blue', 'red']
>>> 

Removing Items From A List

As we can add as many items to a list, they can also be removed from a list. The three ways by which items can be removed are:

#1) Using the del statement

It has the following syntax:

del target_list

The target list(target_list) can be the entire list(in case you want to delete the list) or an item or items in a list(in this case you use indexing or slicing).

Consider the example below.

Say, we want to delete some items from the colors list created above.

>>> colors     # original list
['red', 'blue', 'green', 'yellow', 'black']
>>> c_copy = colors[:] # make a shallow copy to work on
>>> del c_copy[0]  # delete item at index 0
>>> c_copy
['blue', 'green', 'yellow', 'black']
>>> del c_copy[0:2]  # delete items at index 0 and 1(slicing)
>>> c_copy
['yellow', 'black']
>>> del c_copy[:]  # delete all items in a list. Same as ‘c_copy.clear()’
[]
>>> del c_copy  # delete the list object
>>> c_copy      # access object that doesn't exist
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'c_copy' is not defined
>>>

Note: The del statement deletes in place i.e., it will modify the original list object rather than returning a new list object.

#2) Using the list.remove(x)

It removes the first item from the list whose value is equal to x. It raises a ValueError if there is no such item.

This method is used mostly to remove items from a list by name, unlike the del statement that uses indexing and slicing.

>>> colors   # original list
['red', 'blue', 'green', 'yellow', 'black']
>>> c_copy = colors[:]  # create shallow copy to work on
>>> c_copy
['red', 'blue', 'green', 'yellow', 'black']
>>> c_copy.remove('blue')  # remove first item with name 'blue'
>>> c_copy
['red', 'green', 'yellow', 'black']
>>> c_copy.remove('blue')  # try to remove item that doesn't exist
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: list.remove(x): x not in list
>>> 

Note: The list object remove() method deletes in place i.e., it will modify the original list object rather than returning a new list object.

#3) Using list.pop([i])

It removes and returns the item at the given position in a list object. If no i(index) is provided, it removes and returns the last item in the list.

Note: The square bracket around i above doesn’t mean a list of i, rather it means i is optional.

>>> colors             # original list
['red', 'blue', 'green', 'yellow', 'black']
>>> c_copy = colors[:]  # make a shallow copy to work on
>>> c_copy
['red', 'blue', 'green', 'yellow', 'black']
>>> c_copy.pop(3)    # pop out the item at index 3
'yellow'
>>> c_copy
['red', 'blue', 'green', 'black']
>>> c_copy.pop()     # pop out the last item in the list
'black'
>>> c_copy
['red', 'blue', 'green']
>>> 

Note: The list.pop([i]) method deletes in place i.e., it will modify the original list object rather than returning a new list object. Also, it returns the item removed from the list

Replacing Items From A List

Replacing items is pretty simple. In one of the above sections, we saw indexing and slicing. These can be used to access and remove items from a list.

#1) Replace using indexing

L[index] = value
>>> colors   # original list
['red', 'blue', 'green', 'yellow', 'black']
>>> c_copy = colors[:]   # make a shallow copy to work on
>>> c_copy
['red', 'blue', 'green', 'yellow', 'black']
>>> c_copy[0] = 'brown'   # replace item at index 0 with 'brown'
>>> c_copy
['brown', 'blue', 'green', 'yellow', 'black']
>>>

#2) Replacing using slicing

L[n:m] = value

Note: Value should be an iterable, or else the TypeError exception will be raised.

>>> colors   # original list
['red', 'blue', 'green', 'yellow', 'black']
>>> c_copy = colors[:]  # make a shallow copy to work on
>>> c_copy[0:2] = ['brown']  # replace items at index 0 and 1 with 'brown'
>>> c_copy
['brown', 'green', 'yellow', 'black']
>>> c_copy[1:3] = ['white','purple'] # replace items at index 1 and 2 with 'white' and 'purple'
>>> c_copy
['brown', 'white', 'purple', 'black']
>>> c_copy[1:4] = ['white','purple'] # replace items at index 1,2 and 3 with 'white' and 'purple'. Here we replace 3 items with 2 items
>>> c_copy
['brown', 'white', 'purple']
>>>

Frequently Asked Questions

Q #1) What is a list of lists in Python?

Answer: A list of lists in Python is a list that contains lists as its item.

For example

[['a','b'],['c','d']]

It can also be referred to as a nested list.

Q #2) How do you declare a list in Python?

Answer: In Python, a list can be declared in two ways. Either by using the built-in function list() or by using the bracket notation []. list() takes in an iterable and [] takes in items of any type separated by a comma.

[pytyon]>>> list('hello') # a string is iterable
['h', 'e', 'l', 'l', 'o']
>>> [3,4,5,23] # numbers are separated by comma
[3, 4, 5, 23]
>>> 
[/python]

Q #3) Can you put a list in a list Python?

Answer: Yes, we can put a list inside a list. As a matter of fact, a list is a container sequence that takes in items of any data type.

Q #4) What does list() do in Python?

Answer: list() is a built-in function in Python that creates a list object. It takes in an iterable as its argument.

>>> list((3,2,4)) # The iterable object here is a tuple.
[3, 2, 4]
>>> 

Q #5) Can a Python list contain different types?

Answer: A list is a container sequence that takes in items of any data types(list, tuple, integer, float, strings, etc)

More About Lists In Python

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

In this tutorial, we looked at some characteristics of Python Lists along with the various ways of manipulating a list such as creating a list, accessing items from a list, and replacing items from a list.

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.

=> Visit Here To Learn Python From Scratch