List in python programming



Introduction

A list in python programming is the most versatile data structure, which can be written as a list of comma-separated values (items) between square brackets ([]).

my_list = [1, 2, 3]
# my_list is a variable storing a List containing a value 1,2,and 3.

To some extent, lists are similar to arrays in C. One of the differences between them is that all the items belonging to a list can be of different data types and Lists are mutable sequences, typically used to store items.


How to create a list in python

We can create four different types of list as per requirement;

Empty List

Empty list does not contain any value in it.

Example:

this_is_empty_list = []
print(this_is_empty_list)

#output
[]

List of same data type

A List containing same data type;

Example:

#declaring three lists containing same data type
integer_list = [2,4,5,7]
string_list = ["orange", "Banana", "apple"]
float_list = [2.2, 4.0, 10.1]

print(f"Integer list: {integer_list}")
print(f"String list: {string_list}")
print(f"Floating number list: {float_list}")

Output:

Integer list: [2, 4, 5, 7]
String list: ['orange', 'Banana', 'apple']
Floating number list: [2.2, 4.0, 10.1]

List of mixed data type

A list containing different types of data.

Example:

mixed_datatype_list = ["Bhutan", 6.29, 2021]
print(f"mixed_datatype_list example {mixed_datatype_list}")

Output:

mixed_datatype_list example ['Bhutan', 6.29, 2021]

Nested List

We can create list within list and it is called as nested list.

Example:

nested_list = [1, 2, 3, ["a", "b", "c"], 3.5]
print(nested_list)

Output:

[1, 2, 3, ['a', 'b', 'c'], 3.5]



The important characteristics of List in python
list are ordered

Example:

fruits = ["Apple", "Banana", "Mango"]
print("memory address",id(fruits))

fruits = ["Apple", "Mango", "Banana"]
print("memory address", id(fruits))

Output:

memory address 3038751274112
memory address 3038783833408

Note The memory addresses of the list of the fruits containing the same fruits but in different order are stored in different memory addresses, which means that the list is an ordered data structure.


list allows duplicate values

Example:

fruits = ["Apple", "Banana", "Mango", "Apple"]
print(fruits)

Output:

['Apple', 'Banana', 'Mango', 'Apple']

Note In a fruits list an Apple is repeated twice which means that list can contain a duplicate value in it.



list can be indexed and sliced same like string data type
  1. Indexing list(positive indexing)

Example:

fruits = ["Apple", "Banana", "Mango"]
print("The fruit list in index 1 is", fruits[1])

Output:

The fruit list in index 1 is Banana

2. Nested indexing

Example:

fruits = ["Apple", "Banana", "Mango"]
print("The fruit list in index 2 and its first letter is", fruits[2][0])

Output:

The fruit list in index 2 and its first letter is M

3. Negative indexing

Example:

fruits = ["Apple", "Banana", "Mango"]
print("The fruit list in index -3 is an", fruits[-3])

Output:

The fruit list in index -3 is an Apple

4. List slicing

Example:

country = ['B', 'H', 'U', 'T', 'A', 'N']
print("Element from 0 index to 3rd index is", country[0:3])
print("List in reverse order is", country[::-1])
print("Negative slicing", country[-4:-2])

Output:

Element from 0 index to 3rd index is ['B', 'H', 'U']
List in reverse order is ['N', 'A', 'T', 'U', 'H', 'B']
Negative slicing ['U', 'T']



Lists are mutable (changeable)

A value or items inside the list can be changed

Example:

fruits = ["Apple", "Banana", "Mango"]
print("Original list: ",fruits)

fruits[2]= "Guava"
print("Changed list: ",fruits)

Output:

Original list:  ['Apple', 'Banana', 'Mango']
Changed list:  ['Apple', 'Banana', 'Guava']

Note The fruits list at index 2 that is “Mango” was changed to “Guava”.


List supports concatenation

Example:

fruits = ["Apple", "Banana", "Mango"]
animals = ["Cat", "Dog", "Cow"]
print("Concatenating two list: ", fruits + animals)

Output:

Concatenating two list:  ['Apple', 'Banana', 'Mango', 'Cat', 'Dog', 'Cow']



Checking items in the list

Example:

animal = ["Cat", "Dog", "Cow"]
if "Cat" in animal:
    print("Cat is in the animal list")
else:
    print("Cat is not in the list")

Output:

Cat is in the animal list


Looping through a list

Example:

animal = ["Cat", "Dog", "Cow"]
for x in animal:
    print(x)

Output:

Cat
Dog
Cow



The built-in function that can be used in Lists
  1. len() – to find the number of items inside the list.

Example:

animal = ["Cat", "Dog", "Cow"]
print("The total number of items:",len(animal))

Output:

The total number of items: 3

2. min() – to find the minimum value from the list.

Example:

num = [2,1,4,5]
print("The minimum value in the list:",min(num))

Output:

The minimum value in the list: 1

3. max() – to find the maximum value from the list.

Example:

num = [2,1,4,5]
print("The maximum value in the list:",max(num))

Output:

The maximum value in the list: 5



11 List methods

The sequence data type list supports 11 methods in python 3.8 and above. Here are all of the methods of list objects:

list.append(x)

Adds an item to the end of the list.

Example 1:
>>> name = ["Sonam", "Kencho", "Choki", "Tshering", "Dawa"]
>>> name.append("Sangay")
>>> name
Output: 
['Sonam', 'Kencho', 'Choki', 'Tshering', 'Dawa', 'Sangay']

Example 2:
>>> number = [1,3,0.5, 100]
>>> number.append(7**2)  #appending 7 to the power of 2 at the end of the list.
>>> number
Output: 
[1, 3, 0.5, 100, 49]

list.extend(iterable)

Extends the list by appending all the items from the iterable.

Example:
>>> address = ["Zhemgang", "Nangkhor", "Kikher"]
>>> address.extend("me")
>>> address
Output: 
['Zhemgang', 'Nangkhor', 'Kikher', 'm', 'e']

Note: Integer and floating number are not iterable.

list.insert(i, x)

Inserts an item at a given position. The first argument is the index of the element and the next argument is the item to insert in the specified index.

So a.insert(0, x) inserts at the front of the list, and a.insert(len(a), x) is equivalent to a.append(x).

Example 1:
>>> fruits = ["Orange", "mango", "Guava"]
>>> fruits.insert(1, "Apple")
>>> fruits
Output: ['Orange', 'Apple', 'mango', 'Guava']

Example 2:
>>> fruits.insert(len(fruits), "Apple")
>>> fruits
Output: ['Orange', 'Apple', 'mango', 'Guava', 'Apple']

list.remove(x)

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

Example 1:
>>> clas = [7,8,9,10]
>>> clas.remove(7)
>>> clas
Output: 
[8, 9, 10] #7 is removed

>>> clas.remove(10)
>>> clas    #10 is removed
Output: 
[8, 9]

>>> clas.remove(12) #12 is not in the list
Traceback (most recent call last):
  File "<pyshell#66>", line 1, in <module>
    clas.remove(12)
ValueError: list.remove(x): x not in list

>>> clas.remove()   #takes one argument
Traceback (most recent call last):
  File "<pyshell#68>", line 1, in <module>
    clas.remove()
TypeError: remove() takes exactly one argument (0 given)

>>> clas.remove(8,9) # takes exactly one argument
Traceback (most recent call last):
  File "<pyshell#69>", line 1, in <module>
    clas.remove(8,9)
TypeError: remove() takes exactly one argument (2 given)



list.pop([i])

Removes the item at the given position in the list, and returns it. If no index is specified, a.pop() removes and returns the last item in the list. (The square brackets around the I in the method signature denote that the parameter is optional, not that you should type square brackets at that position).

Example 1:
>>> animal = ["Dog", "Cat", "Cow"]
>>> animal.pop()
Output: 'Cow' #last item is popped.

>>> animal.pop(1)
Output: 'Cat' #element at index 1 is popped.

list.clear()

Removes all the items from the list. Equivalent to del a[:].

Example 1:
>>> animal = ["Dog", "Cat", "Cow"]
>>> animal
Output: ['Dog', 'Cat', 'Cow']

>>> animal.clear()
>>> animal
Output: []  #output is empty list

list.index(x[, start[, end]])

Returns zero-based index in the list of the first item whose value is equal to x. Raises a ValueError if there is no such item.

The optional arguments: start and end are used to limit the search to a particular subsequence of the list. The returned index is computed relative to the beginning of the full sequence rather than the start argument.

Example:
>>> animal = ["Dog", "Cat", "Cow"]
>>> animal.index("Dog")
Output: 0    #item “Dog” is at index 0

>>> animal.index("Cow")
Output: 2     #item “Cow” is at index 2

list.count(x)

Returns the number of times x appears in the list.

Example:
>>> animal = ["Dog", "Cat", "Cow"]
>>> animal.append("Dog") #adding item “Dog ” at the end of list.
>>> animal
Output: ['Dog', 'Cat', 'Cow', 'Dog']

>>> animal.count("Dog")
Output: 2  #item “Dog” is found 2 times in the animal list.



list.sort(key=None, reverse=False)

Sorts the items of the list in place. Key specifies a function of one argument that is used to extract a comparison key from each element in iterable (for example, key=str.lower). The default value is None (compare the elements directly).

reverse is a Boolean value. If set to True, then the list elements are sorted as if each comparison were reversed.

Example:
>>> animal = ['Dog', 'Cat', 'Cow']
>>> animal.sort(key = None, reverse = True)
>>> animal
Output: ['Dog', 'Cow', 'Cat']

>>> animal.sort(key = None, reverse = False)
>>> animal
Output: ['Cat', 'Cow', 'Dog']

>>> animal.sort()
>>> animal
Output: ['Cat', 'Cow', 'Dog']

list.reverse()

Reverse the elements of the list in place.

Example:
>>> animal = ['Cat', 'Cow', 'Dog']
>>> animal.reverse()
>>> animal
Output: ['Dog', 'Cow', 'Cat']

list.copy()

Returns a copy of the list.

Example:
>>> animal = ['Cat', 'Cow', 'Dog']
>>> copy_animal = animal.copy()
>>> copy_animal
Output: ['Cat', 'Cow', 'Dog']