Python List


In this section we will learn about the lists in Python. How the Python lists are created, how we can add elements in the list or how we can remove elements from the list.

In Python there are a lot of compound data types and they are referred as sequences. And List is the most widely used sequence in Python, a list is the most versatile data type is Python programming language.

 

How to create a list?

In Python a list can be created by placing elements or items inside square brackets that is []. The items or elements of the list are separated by comma.

A list can have any type of item that an item of the list can be of integer data type, or it can be a floating point number. In Python we can also use nested list. By nested list we mean a list as an item in another list for example:

a = [1, 2, [4, 6]]

Consider the following example in which we have created a number of lists and showed how the items or the elements of the lists differ.

CODE

>>> myList = []

>>> myList = [3, 6, 5]

>>> myList = [1, “Python”, 4.6]

>>> myList = [“Python”, [2, 4, 6]]

In the above example we have created different lists. The first list is an empty list that has no items. The second list has items of same data type that is integer. It is called the list of integers. The third list is a list of items of different data types. It can be seen in the above example that in the list there is an integer value, there is a floating point number and a string. The fourth list shows a nested list that has a string as a first item and another list as its second item.

 

How to access elements from a list?

The following are the different ways to access the elements from a list:

 

List index

In Python the items or elements of the list can be accessed by using the index operator that is []. The index operator directly refers to the element. The index of a list is started from 0 and when we have to access the 4th item of the list then we will write 3 as the index value. A list of 4 items or elements will have the items from 0 to 3.

If the user tries to access an element that is not existing in the list for example our list has 4 items and if the user enters 5 as the index value to access the sixth element of the list then the interpreter will raise an IndexError, because our list only has 4 elements.

The index to access the elements of the list should be an integer; if we use other data type such as if we use a floating point number as the index value then the interpreter will raise an error that is TypeError.

Consider the following example, in which we have declared nested lists and used nested indexing to access the elements of the list:

CODE

>>> myList = [‘e’, ‘t’, ‘y’, ‘u’, ‘d’]

>>> print (myList [3])

>>> print (myList [0])

>>> print (myList [4])

>>> print (myList [5])

>>> nesList = [“Python”, [1, 2, 3]]

>>> print (nesList [0][1])

>>> print (nesList [1][2])

OUTPUT

u

e

d

Traceback (most recent call last):

  File “<pyshell#15>”, line 1, in <module>

    print(myList[5])

IndexError: list index out of range

y

3

3

In the above example, the first list is declared that has simple characters and we used the first print statement to display the index 3 of the list, the index 3 is the letter u and it is print and vice versa.

In the fourth print statement we used the index 5 to display but the interpreter generated an error. The error is generated because our list has only 5 items and index 5 is referring to the 6th item which does not exist.

Then we initialized a nested list, the first element of the list is a string and the second element is another list of simple integer type values. It can be seen in the print statements that we used two indexes as

>>> print (nesList [0][1])

>>> print (nesList [1][2])

The first print statement displays the second element of the string; in the example a string itself is a list. And when we used [0][1] as indexing it displays the second element of the list 1 in the nested list. Similarly in the second print statement the third item of the nested list 2 is printed.

 

Negating Indexing

Negating indexing is allowed in Python for sequences. By negating indexing we mean that the index -1 refers to the last item or element in the list and the index -2 refers to the second last item of the list and so on.

Consider the following example in which we have declared a list and used negating indexing:

CODE

>>> myList = [‘e’, ‘t’, ‘y’, ‘u’, ‘d’]

>>> print (myList [-1])

>>> print (myList [-2])

>>> print (myList [-3])

OUTPUT

d

u

y

y

In the above example, a list is declared and we used negating indexing when index -1 is used the last item of the list that is d is printed and so on.

 

How to slice lists in Python?

A slicing operator that is colon (:), is used to access a range of items in a list.

Consider the following example in which we have used the slicing operator to access a number of elements from the list:

CODE

>>> myList = [‘e’, ‘t’, ‘y’, ‘u’, ‘d’, ‘s’, ‘k’]

>>> print(myList[1:4])

>>> print(myList[:-4])

>>> print(myList[4:])

>>> print(myList[:])

OUTPUT

[‘t’, ‘y’, ‘u’]

[‘e’, ‘t’, ‘y’]

[‘d’, ‘s’, ‘k’]

[‘e’, ‘t’, ‘y’, ‘u’, ‘d’, ‘s’, ‘k’]

7-items

In the above example, a list of items was created having 7 items that is from the index 0 to index 6. The first print statement displays the items from the index 1 to the index 4 and t, y, and u are printed because they fall in the corresponding category.

In the second print statement, the items from index 0 to index 4 are printed. In the third print statement the items from index 5 to end are printed. And in the last print statement all the items of the list are printed when we used only the slicing operator in the square brackets.

 

How to change or add elements to a list?

In Python the items or elements in the list can be changed that is we can say that lists are mutable because they are changeable unlike string type sequence or a tuple. In Python programming an item of the list can be changed by using the assignment operator (=). We can also change a range of items from a list.

Consider the following example in which we have changed elements of the list by using the assignment operator:

CODE

>>> oddNum = [2, 4, 6, 8]

>>> oddNum[0] = 1

>>> print(oddNum)

>>> oddNum[1:4] = [3, 5, 7]

>>> print(oddNum)

OUTPUT

[1, 4, 6, 8]

[1, 3, 5, 7]

oddnum

In the above example a list is declared named oddNum, the list was supposed to have odd numbers but all the items of the list were even numbers. In the line of code the second statement changes the 1st element of the list and makes it equal to 1. And then the list is printed. As you can see that the list has been modified.

In the next statement the range of items in the list are modified to 3, 4 and 7 respectively and the new list is then printed using the print statement. Now we have the oddNum list having odd items.

In a Python list the ‘append ()’ function can be used to one element in a list. To add a number of elements in a list we can use the ‘extend ()’ function.

Consider the following example in which we have used the above methods to add several numbers of elements to our list:

CODE

>>> even = [2, 4, 6]

>>> even. append(8)

>>> print (even)

>>> even. extend ([10, 12, 14])

>>> print (even)

OUTPUT

 [2, 4, 6, 8]

[2, 4, 6, 8, 10, 12, 14]

list-named

In the above example, a list named even was declared and then we used the ‘append ()’ function to add another even number to the list. And the list is printed which had an addition of another even number.

Then we used the ‘extend ()’ function to add a range of items to our list and we added 3 more even numbers, the list is printed and the final list is:

[2, 4, 6, 8, 10, 12, 14]

In Python we can also perform the operation of concatenation that is combining or joining two lists. The operation of concatenation can be performed using the + operator.

Consider the following example, in which we have combined two lists using the + operator:

CODE:

>>> even = [2, 4, 6]

>>> print(even + [8, 10, 12])

OUTPUT:

[2, 4, 6, 8, 10, 12]

even

In the above example a list of even numbers named even was declared and we combined another list to the list named even in the print statement using the + operator.

In Python we can also repeat a list to a given number of times, this can be done by using the * operator. Consider the following example:

CODE:

>>> print ([“Python”] * 4)

OUTPUT:

[‘Python’, ‘Python’, ‘Python’, ‘Python’]

python

In the above example the list having string “Python” is repeated 4 times by using the * operator.

In Python we can also add an item to our desired location in the list. This can be done by using the insert () function. Multiple items can also be inserted in the list by using the slicing operator.

Consider the following example in which we have inserted elements to our list named even using the insert () function:

CODE:

>>> even = [2,8]

>>> even.insert(1,4)

>>> print(even)

>>> even[2:2]= [6, 10]

>>> print(even)

OUTPUT:

[2, 4, 8]

[2, 4, 6, 10, 8]

items-2

In the above example the list named even is declare that has only two items 2 and 8. We used the insert () function to add 4 to the location one of the list and then printed the list. We got 2, 4 and 8.

Then we used the slicing operator to insert two elements in the list at location 3. The final list is then printed and we got:

[2, 4, 6, 10, 8]

 

How to delete or remove elements from a list?

In Python programming the elements from a list can be deleted or removed by using the del keyword. Through the del keyword we can delete the whole list.

Consider the following example, in which we have shown the use of the del keyword with lists to delete an element from the list:

CODE

>>> myList = [‘e’, ‘t’, ‘y’, ‘u’, ‘d’, ‘s’, ‘k’]

>>> del myList [3]

>>> print (myList)

>>> del myList [1:4]

>>> print (myList)

>>> del myList

>>> print(myList)

OUTPUT

NameError: name ‘myList’ is not defined

[‘e’, ‘t’, ‘y’, ‘d’, ‘s’, ‘k’]

[‘e’, ‘s’, ‘k’]

Traceback (most recent call last):

  File “<pyshell#63>”, line 1, in <module>

    print(myList)

deleted

In the above example, a list is declared and then we deleted the item at index 3 that is at location 4, the list is printed and we obtained the desired results. The we deleted a range of items from the list using the slicing operator in combination with the del keyword. And list is printed, it can be seen that now the list is of smaller length. At last we deleted the entire list using the del keyword and when tried to print that list an error will be generated by Python interpreter.

In Python there is a function remove () which is used to remove a given item from the list and also a pop () function to remove an item from a given index or location. If the index is not specified in the pop () function then the last item of the list will be popped out and returned.

The pop () function is used to remove the last item from the list and then returns that last item. The pop () function is used with the stack implementation in data structure (the concept of first in last out that is FILO).

 There is another function called clear () which is used to remove all the items from a list and makes the list empty.

Consider the following example, in which we used all these functions:

CODE:

>>> myList = [‘e’, ‘t’, ‘y’, ‘u’, ‘d’, ‘s’, ‘k’]

>>> myList. remove (‘t’)

>>> print (myList)

>>> print (myList. pop (2))

>>> print (myList)

>>> print (myList. pop ())

>>> print (myList)

>>> myList. clear ()

>>> print (myList)

OUTPUT

[‘e’, ‘y’, ‘u’, ‘d’, ‘s’, ‘k’]

u

[‘e’, ‘y’, ‘d’, ‘s’, ‘k’]

k

[‘e’, ‘y’, ‘d’, ‘s’]

[]

list

In the above example, a list with a number of items is declared. Then we used the remove function to remove an item from the list. The item to be removed is written directly as an argument and we do not have to use index. Then we used the pop () function to pop the item at index 2 or in the location 3 of the list. The item is popped and returned; whenever an item is popped it is deleted from the list.

Then we popped another item from the list this time we did not pass any arguments that is the index of the item to be popped and the interpreter itself popped the last item from the list. In the end the list was cleared using the clear () function.

It can be noticed here that when a list is cleared all the items are deleted and not the whole list that is why when we printed the list after using the clear () function we had an empty list.

The items from a list in Python can also be deleted by assigning an empty list to a slice of elements. Consider the following example:

CODE

>>> myList = [‘e’, ‘t’, ‘y’, ‘u’, ‘d’, ‘s’, ‘k’]

>>> myList[3:4] = []

>>> print(myList)

>>> myList[2:5]

OUTPUT

[‘e’, ‘t’, ‘y’, ‘d’, ‘s’, ‘k’]

[‘y’, ‘d’, ‘s’]

index-three

In the above example, the item at index three is assigned the empty list and hence this item is deleted and so on.

 

Python List Methods:

In Python programming there are some methods or functions that are related to list and they use the list objects. These methods are accessed as list.method (). Consider the following table in which we have explained some of the list methods:

Methods Description
append (x) This function is used to add an item x to the end of the list.
extend (l) This function is used to add all the items l to the end of the list.
insert (i, x) This method is used to insert an element x in the list at position i.
remove (x) This method is used to remove the first item from the list and it will be equal to x in the list.
pop ([i]) This method is used to remove and return an item at the position i. If the position is not specified the last item of the list will be removed and returned.
clear () This method is used to remove all the items from the list. It makes the list empty.
index (x) This method is used to return the index of the first item in the list that will be equal to x.
count (x) This method is used to return the number of items in the list and that will be equal to x.
sort () This method is used to sort items in the list. The items will be sorted in ascending order.
reverse () This method is used to reverse the order of the items or elements in the list.
copy () This method is used to return a shallow copy of the list.

Consider the following example, in which we have used some of the methods of list:

CODE

>>> myList = [3, 5, 7, 2, 8, 9, 4, 1]

>>> print (myList. index (9))

>>> print (myList. count (3))

>>> myList. sort ()

>>> print (myList)

>>> myList. reverse ()

>>> print (myList)

OUTPUT

5

1

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

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

first-print-statement

In the above example, a list is declared and in the first print statement the index method of the list is used. WE passed 9 as an argument to check at which index number the digit 9 is in the list. The output is 1.

Then in the second print statement we used the count method of the list that counts that how many times an item is existing in the list, as 3 is only one time therefor, 1 is printed. Then we used the sort () method of the list to sort the list in ascending order and printed the list, the list is now arranged. The last function that we used is the reverse function, the reverse function is used reverse the items of the list, the list is printed.

 

List Comprehension: Elegant way to create new list

In Python programming we can create a new list from already existing list. The list comprehension is the best way to do so. A list comprehension has an expression that is followed by the ‘for statement’ inside the square brackets.

Consider the following example in which we have created a list from already existing list by adding 2 in each of the item or element of the list:

CODE

>>> myList = [2+i for i in range (10)]

>>> print (myList)

OUTPUT

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

list

In the above example, a list is created in which we used list comprehension with ‘for statement’, 2 is added to the counter variable and the counter variable is from 1 to 10. The newly created a list is printed that has even numbers.

The following method can also be used to do the same thing:

CODE

>>> myList = []

>>> for i in range (10):

          myList. append (2+i)

>>> print (myList)

OUTPUT

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

in-the-above-example

In the above example, an empty list is created and then we used the ‘for statement’ from 0 to 10 and then used the append method to add item to the list. In the append method we passed 2+i as the argument. Here i is the counter variable, in each value of the counter variable 2 is added and the newly created list is printed.

With the list comprehension we can also use the ‘if statement’. The ‘if statement’ is used to filter the items of the list. Consider the following example in which we have used the list comprehension with ‘if statement’:

CODE

>>> myList = [2 +i for i in range (10) if i >3]

>>> myList

>>> even = [i for i in range (20) if i%2==0]

>>> even

>>> [a + b for a in [‘Hello’, ‘Hello’] for b in [‘World’, ‘World’]]

OUTPUT

[6, 7, 8, 9, 10, 11]

[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

[‘HelloWorld’, ‘HelloWorld’, ‘HelloWorld’, ‘HelloWorld’]

helloworld

In the above example, a list is declared but the items of the list are not specified rather we used the ‘for and if statements’ with the list comprehension. We used the condition that in each of the value of the counter variable we added 2 and if the resulting value is greater than 3 then the items will be printed.

Then we declared another list named even in which we added the condition that if each of the value of the counter variable after addition of 2 is divisible by 2 then print the item and in this way the list of even numbers are printed.

Then we created another list in which we have added or joined or concatenated two lists having strings as items using the ‘for statement’ and the assignment operator (+), in the end list is printed.

 

Other List operations in Python

 

List Membership Test

In Python we can test an item in the list by using the keyword in. By testing an item in the list we mean that if the item exists in the list or not.

Consider the following example in which we have declared a list and checked if any item of the list exists in the declared list or not by using the keyword Python:

CODE

>>> myList = [‘e’, ‘t’, ‘y’, ‘d’, ‘w’, ‘q’, ‘s’, ‘x’]

>>> print (‘w’ in myList)

>>> print (‘r’ in myList)

>>> print (‘q’ in myList)

OUTPUT

True

False

True

true

In the above example a list named myList is created that has characters and used the in keyword in the print statement to check if the item exists in the list or not. If the item is found in the list True will be returned by the interpreter and False if the item is not found in the list.

 

Iterating Through a List

In Python we can iterate through each item of the list by using the ‘for statement’. Consider the following example in which we have used the ‘for statement’ to iterate through the items of the list:

CODE

>>> for desert in [‘Custard’, ‘Trifle’, ‘Pie’]:

          print (“I like to eat”, desert)

OUTPUT

I like to eat Custard

I like to eat Trifle

I like to eat Pie

i-like-to-eat-pie

In the above example, we have used ‘desert’ as the counter variable to iterate through the list and then printed the list using the counter variable.

 

Built in Functions with List

In Python there are many built in functions such as all (), len (), min () etc. Consider the following table in which we have described the commonly used functions in Python for lists:

Function Description
all () This function is used to return a true if all the elements in the list are true and if the list is empty.
any () This function is used to return a true if any of the elements in the list are true and returns a false if the list is empty.
enumerate () This function is used to return an enumerate object. The enumerate function has the index and the value of all the items of the list as a tuple.
len () This function is used to return the length of the list or the number of the elements in the list.
list () This function is used to return an iterable (tuple, string, set, dictionary) to a list.
max () This function is used to return the largest item in the list.
min () This function is used to return the smallest item of the list.
sorted () This function is used to a new sorted list. The sorted () function does not sort the list itself but it returns the already sorted list.
sum () This function is used to return the sum of all the elements in the list.