5  Lists

A collection of items, in python, is refered to as a list. A list can have elements of same data type or multiple data types. A list is denoted by square brackets ([]). The indexing of elements in a list starts from zero. To access an element by its index we can specify index in square brackets after the list name. Slicing of lists can be performed as well.

fruits = ["apple", "banana"]
print(type(fruits))
print(fruits)
print(fruits[1])
<class 'list'>
['apple', 'banana']
banana
numbers = [10,20,30,40,50]
print(numbers)
print(numbers[1:4]) # slicing
[10, 20, 30, 40, 50]
[20, 30, 40]

5.1 Modifing contents of a list

A list is a mutable data type i.e. the contents of the collection can be changed. The append and extend functions adds an element or a collection of elements to a list. To add an element at a specified position within the list, the insert function can be used.

fruits.append("mango")
print(fruits)
print(len(fruits))
['apple', 'banana', 'mango']
3
fruits = ["apple", "banana"]
fruits2 = ["pineapple","cherry"]
fruits.append(fruits2) #adding a list using append
print(fruits)
print(len(fruits))

fruits = ["apple", "banana"]
fruits2 = ["pineapple","cherry"]
fruits.extend(fruits2) #adding a list using extend
print(fruits)
print(len(fruits))
['apple', 'banana', ['pineapple', 'cherry']]
3
['apple', 'banana', 'pineapple', 'cherry']
4
fruits.insert(1,"grapes")
print(fruits)
['apple', 'grapes', 'banana', 'pineapple', 'cherry']
# slicing
print(fruits[1:4])
['grapes', 'banana', 'pineapple']

To remove the last element from a list, pop function can be used. It returns a the last element and the original list is shortened by one element. To remove an element by its name use the remove function. Note that if a list has duplicate elements then the remove function would delete only the first occurance of that element.

last_fruit = fruits.pop()
print(fruits)
print(last_fruit)
['apple', 'banana', 'pineapple']
cherry
fruits.remove("banana")
print(fruits)
['apple', 'pineapple']

5.2 List functions

There are some useful functions available to manupulate lists. These functions act in place i.e. these functions do not return anything and just modifies the original list.

fruits = ['apple', 'banana', 'mango', 'pineapple', 'cherry', 'banana']
print(fruits.count("banana"))
fruits.reverse()
print(fruits)
fruits.sort()
print(fruits)
fruits.sort(reverse=True)
print(fruits)
2
['banana', 'cherry', 'pineapple', 'mango', 'banana', 'apple']
['apple', 'banana', 'banana', 'cherry', 'mango', 'pineapple']
['pineapple', 'mango', 'cherry', 'banana', 'banana', 'apple']

Quiz: Given a list nums=[1,2,3,4,5]. Write a code to print 4.

Show answer
nums = [1,2,3,4,5]
print(nums[3])