Everything technical on List in Python

MarsDevs
12 min readOct 6, 2022

--

In this article, MarsDevs presents you with the technical information on Python list, its syntax, examples, and different operations on python list.

What do we mean by Python List?

Although there are many data structures in Python, the sequence is the most basic one among them. The sequence starts from zero indexes and goes up to the length of sequence -1.

Python List is used for storing the sequence of different data types. A list is a mutable (can be changed or modified) data type which implies we can change the elements of a list even after they have been formed. We can perform many operations on the list like adding, subtracting, multiplying, slicing and comparing, etc.

Here is the example of List,

# Here is the list of fruits.
myFruitList = [“Apple”, “Mango”, “Banana”, “Grapes”, “PineApple”]

# Printing the list.
print(myFruitList)

Output :

[‘Apple’, ‘Mango’, ‘Banana’, ‘Grapes’, ‘PineApple’]

Syntax of List :

In the list, the elements are enclosed within square brackets ([]) and separated by comma (,).

Here is the example of a list containing different types of data,

# Here is the list.
# Containing different types of data.
myList = [1, “Apple”, 2.0, “Banana”, “V”, “Grapes”, True]

# Printing the list.
print(myList)

Output :

[1, ‘Apple’, 2.0, ‘Banana’, ‘V’, ‘Grapes’, True]

In the above example, the list contains different data types (like integer, floating point, string, boolean) all separated by commas and enclosed within square brackets.

Parameters of List -

Python List constructor takes a single argument which is nothing but the collection or sequence like tuples, string, set, and dictionary.

Here is the example,

# Here is the list.
# Containing taking parameter of String and Tuple.

# Declaring String.
myString = “Python”

# Declaring Tuple.
myTuple = (“a”, “b”, “c”, “d”, “e”)

# Taking the parameter of the list and printing them.
print(list(myString))
print(list(myTuple))

Output :

[‘P’, ‘y’, ‘t’, ‘h’, ‘o’, ‘n’]

[‘a’, ‘b’, ‘c’, ‘d’, ‘e’]

In the above example, we can notice that the list() method changes the sequence from String and Tuple into List without altering the order of elements sequence.

Return Values of list() -

Here we will compare two lists so as to know more about the return type of list.

Example-1:

# Here is an example to know.
# Know about the return type of list.

# Declaring and Initialising 2 lists.
x = [1, 2, “Ram”, 2.5, “Shyam”, 5.4]
y = [1, 2, 5.4, “Ram”, 2.5, “Shyam”]

# Comparing the lists to get the return type of list.
print(x == y)

Output :

False

Example-2:

# Here is the example to -
# know about the return type of list.

# Declaring and Initialising 2 lists.
x = [1, 2, “Ram”, 2.5, “Shyam”, 5.4]
y = [1, 2, “Ram”, 2.5, “Shyam”, 5.4]

# Comparing the lists get the return type of list
print(x == y)

Output :

True

In the above 2 examples, we can see both lists have the same number of elements but the ordering is different. The example in which both lists have the same elements and in the same order returns True while other examples return False.

Python List Methods -

Python has 6 data types that are used for storing the sequence but the list is the most common and stable among them.

Here are the different list methods -

1. append() — This method will add a new element to the end of the list.

# Adds List Element as value of List.
list = [‘Narendra’, ‘Modi’, 1950]
list.append(‘Lok Kalyan Marg’)
print(list)

It prints -

[‘Narendra’, ‘Modi’, 1950, ‘Lok Kalyan Marg’]

2. extend() — This method extends the list by adding all specified iterables like tuple, and list at the end of the list.

list = [‘Narendra’, ‘Modi’, 1950]
list1 = [1, 2, 3]
list2 = [2, 3, 4, 5]

# Add List2 to List1
list1.extend(list2)
print(list1)

# Add List1 to List2 now
list2.extend(list)
print(list2)

It prints -

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

[2, 3, 4, 5, ‘Narendra’, ‘Modi’, 1950]

3. insert() — This method is used for inserting elements at the specified index.

list = [‘Narendra’, ‘Modi’, 1950]
# Insert at index 2 value 10087
list.insert(2, ’17 September’)
print(list)

It prints -

[‘Narendra’, ‘Modi’, ’17 September’, 1950]

4. remove() — This method is used to remove the first occurrence of the specified element from the list.

list = [‘Narendra’, ‘Modi’, 1950, ‘Chief Minister’]
# Remove value — ‘Chief Minister’
list.remove(‘Chief Minister’)
print(list)

It prints -

[‘Narendra’, ‘Modi’, 1950]

5. pop() — This method is used to remove the element at the specified index. If the index is not passed by default it will remove the last element of the list.

list = [‘Narendra’, ‘Modi’, 1950, ‘Chief Minister’, ‘Prime Minister’]
# Remove value at Index 3 — ‘Prime Minister’
list.pop(3)
print(list)

It prints -

[‘Narendra’, ‘Modi’, 1950, ‘Prime Minister’]

6. clear() — It will remove/delete all the elements of the list.

list = [‘Narendra’, ‘Modi’, ’17 September’, 1950]
# Removing all items from the list
list.clear()
print(list)

It prints -

[]

7. sort() — This method will sort the elements of the list in ascending order.

list = [150, 100, 200, 105, 99, 76, 10, 95, 10, 1]
# Sort the list
list.sort()
print(list)

It prints -

[1, 10, 10, 76, 95, 99, 100, 105, 150, 200]

8. count() — This method will return the count of elements present in the given argument.

list = [150, 100, 2, 105, 99, 2, 10, 95, 2, 1]
# Count the occurrence of 2
print(list.count(2))

It prints -

3

9. copy() — It will return the copy of the list.

list = [‘Narendra’, ‘Modi’, ’17 September’, 1950]
# Copying the list to list2
list2 = list.copy()
print(list2)

It prints -

[‘Narendra’, ‘Modi’, ’17 September’, 1950]

10. reverse() — This method will reverse the index location of the elements in the list. The first element will be indexed last, the second with the second last, and so on.

list = [‘Narendra’, ‘Modi’, ’17 September’, 1950]
# Reversing the list
list.reverse()
print(list)

It prints -

[1950, ’17 September’, ‘Modi’, ‘Narendra’]

11. max() — returns maximum in the list.

list = [150, 100, 200, 105, 99, 76, 10, 95, 10, 1]
# Max in the list
list.sort()
print(max(list))

It prints -

200

12. min() — returns minimum in the list

list = [150, 100, 200, 105, 99, 76, 10, 95, 10, 1]
# Min in the list
list.sort()
print(min(list))

It prints -

1

13. index() — returns index of first occurrence of a number.

list = [150, 100, 102, 105, 99, 2, 10, 95, 2, 1]
# Count the occurrence of 2
print(list.index(2))

It prints -

5

14. len() — returns size or length of the given list.

list = [‘Narendra’, ‘Modi’, ’17 September’, 1950]
# Size of the list
print(len(list))

It prints -

4

Now let’s discuss these methods in a more detailed way with the help of examples.

As discussed earlier python list is a collection of distinct types of elements like integer, string, and boolean, all enclosed within square brackets and elements separated by commas. A list can be empty and can have more than 1 element, there is also a concept of a nested list in which we can add a list inside another list. Like-

# Here is the example to know
# more about the types of list.

# Empty list.
empty_list = []

# Printing the empty list.
print(empty_list)

# List with items.
simple_list = [1, 2, 3, 4, 5]

# Printing this list.
print(simple_list)

# List within in another list -
# i.e nested list.
nested_list = [True, 6, [1, 2.0, “Bye”], 5.0, “Hello”]

# Printing the nested list.
print(nested_list)

Output :

[]

[1, 2, 3, 4, 5]

[True, 6, [1, 2.0, ‘Bye’], 5.0, ‘Hello’]

Accessing the list elements -

We can access the elements of the list by using the index operator []. In Python, the index starts from 0 and goes from up there, if there is a list containing 10 elements, then the index will range from 0–9. Also, if we try to access the element out of range then we get index out of range error. Only integers must be used as the index, otherwise, python will raise TypeError.

# Here is the example to know -
# How to access different elements of the list.

# Creating a sample list.
sample_list = [“p”, “y”, True, “t”, 2.0]

# Accessing first element.
print(sample_list[0])

# Accessing fifth element.
print(sample_list[4])

# Trying to access with float index -
# but it will give an error.
print(sample_list[2.0])

Output :

p

2.0

— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — -

TypeError Traceback (most recent call last)

<ipython-input-3–1cb4d2d5ae51> in <module>

13 # trying to access with float index

14 # but it will give an error

— -> 15 print(sample_list[2.0])

TypeError: list indices must be integers or slices, not float

The elements of the nested list can also be accessed. The negative indexing is also supported by python, where the last element is represented by the index -1, the second last by -2, and so on.

# Here is the example showing how
# to access the nested list elements and use negative indexing.

# Creating a sample nested list.
nested_list = [[“1”, “2”, True], “y”, True, [“hello”], 2.0]

# Nested accessing.
print(nested_list[3][0])
print(nested_list[0][2])

# Accessing the last element.
print(nested_list[-1])

# Accessing the second last element.
print(nested_list[-2][0])

Output :

hello

True

2.0

hello

List Slicing -

In order to access the sub-list of elements in a list, we can use the slicing operator( : ). The syntax for slicing the list is as follows -

list_name[start : stop : step]

  • Start tells about the starting index of the sublist with respect to the given list
  • Stop tells about the stopping index of the sublist with respect to the given list.
  • Step can be used to skip every nth element in the range.

# Here is the example showing -
# how to perform slicing in python list.

# Create a sample list.
sample_list = [‘A’,’E’,’I’,’O’,’U’, ‘B’, ‘C’, ‘D’, ‘F’]

# Print elements from index 0 to index 3.
print(sample_list[0:4])

# Print elements from index 5 to end.
print(sample_list[4:])

# Print elements from beginning to end by taking 3 steps each time.
print(sample_list[::3])

Output :

[‘A’, ‘E’, ‘I’, ‘O’]

[‘U’, ‘B’, ‘C’, ‘D’, ‘F’]

[‘A’, ‘O’, ‘C’]

Adding/Changing the list elements -

Unlike String and Tuples, lists are mutable i.e they can be updated. We can use the assignment operator (=) to update a single element or a group of objects. The append() method is used to add a single element to the end of the list and extend() method is used to add several elements.

# Here is the example showing -
# working of append() and extend() method.

# Sample list.
prime = [2, 3, 5, 7, 11, 13]

# Adding a single element using the append() method.
prime.append(17)

print(prime)

# Adding multiple elements using extend() method.
prime.extend([19, 23, 29])

print(prime)

Output :

[2, 3, 5, 7, 11, 13, 17]

[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]

Moreover, we can combine or concatenate two lists using the + operator. Also, the * operator is used to repeat a list a given number of times.

# Here is the example showing -
# working of + and * operator.

# We have a sample list.
sample = [10, 20, 30]

# Adding new list in above one using + operator.
print(sample + [40, 50, 60])

# Repeating the list 5 times using * operator.
print([“Hey !!”] * 4)

Output :

[10, 20, 30, 40, 50, 60]

[‘Hey !!’, ‘Hey !!’, ‘Hey !!’, ‘Hey !!’]

The insert() method is also used to add elements at a certain index in the list. Its syntax is like -

list_name.insert(index, element)

# Here is the example showing -
# working of insert() method

# We have a sample list.
sample = [10, 20, 30]

# Inserting 50 at index 1.
sample.insert(1, 50)

print(sample)

Output :

[10, 50, 20, 30]

Deleting List elements -

If we know the index of the element which we want to delete then we can use the del method, otherwise use the remove() method.

# Here is the example of deleting -
# element/s from the list.

# creating a sample list.
sample_list = [“N”, “A”, “R”, “E”, “S”, “H”]

# Deleting item at index 5.
del sample_list[5]

print(sample_list)

# Deleting multiple items from index 0 to 2.
del sample_list[0:3]

print(sample_list)

Output :

[’N’, ‘A’, ‘R’, ‘E’, ‘S’]

[‘E’, ‘S’]

Suppose, we want to delete an entire list and then use the del method.

# Here is the example showing the usage of -
# del method in the list,

# Creating a sample list.
sample_list = [“N”, “A”, “R”, “E”, “S”, “H”]

# Deleting the entire list.
del sample_list

print(sample_list)

Output :

NameError Traceback (most recent call last)

<ipython-input-7-b2385fb25d7a> in <module>

8 del sample_list

9

— -> 10 print(sample_list)

NameError: name ‘sample_list’ is not defined

The remove() method is used to remove a specific element and pop() is used to get rid of an element at a specific index. If no position is passed in the pop() method, then it will remove and return the last element of the list by default.

# Here is the example showing the working of -
# remove() and pop() method in the list.

# Creating a sample list.
sample_list = [“C”, “O”, “D”, “I”, “N”, “G”]
# Use of remove() method
sample_list.remove(“D”)

# printing the output
print(sample_list)

# use of pop() method
print(sample_list.pop(1))

# printing the output
print(sample_list)

# pop without index by default deletes the last element
print(sample_list.pop())

# printing the output
print(sample_list)

# deletes all the elements from the list
sample_list.clear()

print(sample_list)

Output :

[‘C’, ‘O’, ‘I’, ’N’, ‘G’]

O

[‘C’, ‘I’, ’N’, ‘G’]

G

[‘C’, ‘I’, ‘N’]

[]

  • List Comprehension : List comprehension is the simplest and efficient way of generating new lists from iterables like tuples, arrays, strings, etc.

A list comprehension is made of brackets that will hold the expression that is run for each element.

# Here is the example showing -
# use of list comprehension

mul_list = [i * 3 for i in range(1, 12)]
print(mul_list)

even_squares = [i**2 for i in range(2, 10) if i % 2 == 0]
print(even_squares)

Output :

[3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33]

[4, 16, 36, 64]

--

--

MarsDevs

We are a product development shop using tech involving python, nodejs, reactjs, vuejs, reactnative, flutter, docker, aws, gcp, kubernetes