Python List

Python list is an ordered collection of data types like Integer, Strings, and Objects. Lists are the Python equivalent of arrays in other languages, but Lists are more powerful and versatile. Lists are mutable themselves; hence, they can be altered and store mutable elements, and elements in a list can be heterogeneous or homogeneous.

How to create a list in Python?

The Python lists are created using the square brackets "[ ]" and include the elements separated by commas inside. These elements can also be mutable, like lists, sets, dictionaries, etc. A list can contain different item types like a string, number, objects, variable, or another list. The list's items can be homogeneous or non-homogeneous and can have a mix of strings, numbers, or another list.

You can create an empty list without any items.

list_name = [ ]

Syntax

list_name = [item1, item2, item3,……., item_n]

How to create a simple Python list.

			

my_list = [1,2,3,4,5] #creating a list
print(my_list)

				

Output:

[1, 2, 3, 4, 5]

How to create simple Python nested lists.

			

my_list = [1,2,[5,6,7],3,4] #creating a list with mutable elements
print(my_list)

				

Output:

[1, 2, [5, 6, 7], 3, 4]

How do you access elements of a list?

Since lists are ordered in nature, each List element carries a unique index. A particular element in the list can be accessed by referencing it through its index. You can access the specific element of the list by mentioning the index number in the square brackets.

Like this:

			

my_list = [1,2,"Mango",3,[1,2,4]]
print(my_list[2])   #accessing the 3rd element of the list
print(my_list[4])   #accessing the 5td element of the list
print(my_list[1])   #accessing the 2nd element of the list

				

Output:

Mango [1, 2, 4] 2

Note that the index in a List starts from 0. Meaning that the first element is at the 0th index, the 2nd element is at the 1st index, the 3rd element at the 2nd index and so on.

We can also specify negative indices to the list. The negative index allows us to access elements by referencing them relative to the end of the list. For example, the -1 index will retrieve the last element in the list.

			

my_list = [1,2,"Mango",3,[1,2,4]]
print(my_list[-1])
print(my_list[-2])
print(my_list[-3])

				

Output:

[1, 2, 4] 3 Mango

How do you modify elements in a List?

There are multiple ways to add more elements to a List. We can use the "=" operator to assign a new value to a specified index in a list.

			

my_list = [1,2,"Mango",3,[1,2,4]]
my_list[2] = "Orange"
print(my_list[2])   #accessing the 3rd element of the list

				

Output:

Orange

To add new elements to the list, we use the append() function. Like this

			

my_list = [1,2,"Mango",3,[1,2,4]]
my_list.append("Cherry")
print(my_list)

				

Output:

[1, 2, 'Mango', 3, [1, 2, 4], 'Cherry']

The extend() function can be used to append multiple elements simultaneously to a list. Like this

			

my_list = [1,2,"Mango",3,[1,2,4]]
my_list.extend(["Banana", 5, 9])
print(my_list)

				

Output:

[1, 2, 'Mango', 3, [1, 2, 4], 'Banana', 5, 9]

We can insert elements at a specified index range using the insert() function. This is similar to using the "=" operator for inserting.

			

my_list = [1,2,"Mango",3,[1,2,4]]
my_list.insert(1, ["Apple"])
print(my_list)

				

Output:

[1, ['Apple'], 2, 'Mango', 3, [1, 2, 4]]

How to remove a List element?

There are various methods to remove elements from a list. One method is to use the remove() function. Pass the element as an argument you want to remove.

			

my_list = [1,2,"Mango",3,[1,2,4]]
my_list.remove(1)
print(my_list)

				

Output:

[2, 'Mango', 3, [1, 2, 4]]

The pop() function removes the last element and returns it. If you want to remove any other element, specify its index.

			

my_list = [1,2,"Mango",3,[1,2,4]]
my_list.pop() #deletes the last index element
print(my_list)
my_list.pop(0) #deletes the 0th index element
print(my_list)

				

Output:

[1, 2, 'Mango', 3] [2, 'Mango', 3]

The del() function can be used to remove the element from a List by specifying the index position. You can remove a single element, multiple elements, or the entire list.

			

my_list = [1,2,"Mango",3,[1,2,4]]
del my_list[2]
print(my_list)

				

Output:

[1, 2, 3, [1, 2, 4]]

Deleting the complete list.

			

my_list = [1,2,"Mango",3,[1,2,4]]
del my_list
print(my_list)

				

Output:

NameError: name 'my_list' is not defined

The clear() function can be also used to achieve the same functionality. But one difference between deleting the whole list using del operator and using clear() function is that the del operator deletes the pointer to the list from memory. That is why we get the "name not defined" error. On the other hand, the clear() function only deletes the list elements.

Thus, making a list empty. Check out the code and its output below for a better understanding

			

my_list = [1,2,"Mango",3,[1,2,4]]
my_list.clear() #only deletes the elements in the list and not the pointer to the list
print(my_list) # will return an empty list

				

Output:

[]

List Slicing

List slicing is a very powerful feature in Python. It allows the programmer to access and modify multiple elements in a list. The basic slice expression looks like this

List[start:stop:step]

Start is the index from where the slicing begins. Its default value is 0 or the start of the list.

Stop is the index where the slice ends. Its default value is the end of the list.

Step is the increment. Its default value is 1.

For example

			

my_list = [1,2,"Mango",3,[1,2,4],"Cherry", 55.2]
print(my_list[:2])
print(my_list[2:])
print(my_list[1:4:2])
print(my_list[-1:2:-2])

				

Output:

[1, 2] ['Mango', 3, [1, 2, 4], 'Cherry', 55.2] [2, 3] [55.2, [1, 2, 4]]

List comprehension

Another powerful feature of Python List is that it allows the programmer to generate lists quickly and easily. The elements of the list are generated based on a formula. Given below is an example of list comprehension.

			

my_list = [x*x for x in range(10)] # x*x is the formula
print(my_list) # will return the list containing the squares of numbers between 0 and 9

				

Output:

[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

The above code is equivalent to

			

my_list = []
for x in range(10):
	my_list.append(x*x)
print(my_list)

				

Available List methods in Python

These are the List functions supported by Python.

Function Description
list.append(element) An element is appended at the end
list.extend(list2) Appends the list2 to the end
list.insert(index, element) Inserts the element at the mentioned index
list.remove(element) An element is removed
list.pop(element) An element is removed and returns it.
list.clear() All elements are deleted
list.count(element) Count the number of occurrences of the element
list.sort() Sort elements in ascending order
list.reverse() Reverse the order of elements
list.copy() Return a copy of the list
list.index(element) Return the first index of the element passed as a parameter