Lists in Python

Lists in Python with Examples

In this article, I am going to discuss Lists in Python with examples. Please read our previous article where we discussed Modules and Packages in Python with examples. As part of this article, we are going to discuss the following pointers which are related to Lists in Python.

  1. Python Data structures
  2. Sequence of elements
  3. What is List in Python
  4. Creating list
  5. Difference between list() function and list class
  6. Mutability
  7. Accessing elements in list
  8. Important functions and methods in list
  9. Difference between append and insert
  10. Difference between remove() and pop() methods
  11. Ordering elements of List:
  12. Aliasing and Cloning of list objects
  13. Mathematical + and * operators
  14. Comparison of lists
  15. Membership operators
  16. Nested Lists
  17. List comprehensions
Python Data Structures:

In python, there are quite few data structures available. They are used to store a group of individual objects as a single entity.

Sequences

Sequences are those, which contains a group of elements, whose purpose is to store and process a group of elements. In python, strings, lists, tuples and dictionaries are very important sequence data types.

Lists in Python:

A list is a data structure which can store a group of elements or objects. It has the following features/properties:

  1. Lists can store the same type as well as different types of elements. Hence, it is heterogeneous.
  2. Lists have dynamic nature which means we don’t need to mention the size of the list while declaring as we do for arrays in other programming languages. The size will increase dynamically.
  3. Insertion order is preserved. The order, in which the items are added into a list, is the order in which output is displayed.
  4. List can store duplicates elements.
  5. In lists index plays the main role. Using index we perform almost all the operations on the items in it.
  6. List objects are mutable which means we can modify or change the content of the list even after the creation.
Creating a list in Python

There are a couple of ways to create a list in Python. Let’s see them with examples.

Creating a list in Python by using square brackets ‘[]’

We can create a list in python by using square brackets ‘[]’. The elements in the list should be comma separated.

Example: Creating an empty list (demo1.py)

l1 = []
print(l1)
print(type(l1))

Output:

Creating a list in Python by using square brackets ‘[]’

Example: Creating a list with elements (demo2.py)

names = ["Mohan", "Prasad", "Ramesh", "Mohan", 10, 20, True, None]
print(names)

Output: Lists in Python in Detail with Examples

You can observe from the output that the order is preserved and also duplicate items are allowed. It can contain mixed data type(strings, integers, boolean, None) elements.

Creating a list in Python by using list() function

You can create a list by using list() function in python. Generally, we use this function for creating lists from other data types like range, tuple etc. This is generally referred to as type conversion

Example: Creating a list using list() function (demo3.py)

r=range(0, 10)
l=list(r)
print(l)

Output: Creating a list in Python by using list() function

Difference between list() function and list class in python:

list() is a predefined function in python. list() function is used to convert other sequences or data types into list data types

list is predefined class in python. Once we create a list then it is internally represented as a list class object type. We can check this by using a type function.

Example: Creating a list using list() function (demo3.py)

r=range(0, 10)
l=list(r)
print(l)
print(type(l))

Output:

Difference between list() function and list class in python

Example: Mutability (demo4.py)
l = [1, 2, 3, 4, 5]
print(l)
print("Before modifying l[0] : ",l[0])
l[0]=20
print("After modifying l[0] : ",l[0])
print(l)

Output:

Mutability in Python

Accessing A List in Python:

There are three ways in which you can access the elements in the list in python. They are:

  1. By using indexing
  2. By using slicing operator
  3. By using loops
Accessing List By using indexing in Python:

This way is the same as we have seen for string data type. Accessing the elements by index means, accessing by their position numbers in the list. Index starts from 0 onwards. List also, just as strings, supports both positive and negative indexes.

Positive index represents from left to right direction and negative index represents from right to left direction.

Accessing List By using indexing in Python

Note: IndexError: If we are trying to access beyond the range of list index, then we will get IndexError.

Example: List Indexing (demo5.py)
names = ["Prabhas", "Prashanth", "Prakash"]
print(names)
print(names[0])
print(names[1])
print(names[2])
print(type(names))
print(type(names[0]))
print(type(names[1]))
print(type(names[2]))

Output:

Accessing List By using indexing in Python

Example: List index out of range error (Demo6.py)
names = ["Prabhas", "Prashanth", "Prakash"]
print(names)
print(names[0])
print(names[1])
print(names[2])
print(names[10])

Output:

List index out of range error

Accessing List By using slicing operator in Python

Slicing is the way of extracting a sublist from the main list. The syntax is given below.

list_name[start: stop: stepsize]

start represents the index from where we slice should start, default value is 0. stop represents the end index where slice should end. The max value allowed is the length of the list. If no value is provided, then it takes the last index of the list as default value. stepsize represents the increment in the index position of the two consecutive elements to be sliced. The result of the slicing operation on the list is also a list i.e it returns a list.

Example: Slicing (Demo7.py)
n = [1, 2, 3, 4,5, 6]
print(n)
print(n[2:5:2])
print(n[4::2])
print(n[3:5])

Output:

Accessing List By using slicing operator in Python

Accessing List By using loops in Python:

We can also access the elements of a list using for and while loops

Example: Accessing list using loops (demo8.py)

a = [100, 200, 300, 400]
for x in a:
   print(x)

Output:

Accessing List By using loops in Python

Example: Accessing list using loops (demo9.py)

a = [100, 200, 300, 400]
x = 0
while x<len(a):
   print(a[x])
   x = x+1

Output:

Lists in Python in Detail with Examples

IMPORTANT FUNCTIONS OR METHODS OF LISTS IN PYTHON

In python, a method and a function are one and the same. There is not much difference between them. It will be clearly explained in the OOPS concepts. For now just remember function and method are the same.

len() method in python:

This function when applied on a list will return the length of the elements in it.

Example: len() function (demo10.py)

n = [1, 2, 3, 4, 5]
print(len(n))

Output: 5

count() function in Python:

This method returns the number of occurrences of specific item in the list

Example: count() method (demo11.py)

n = [1, 2, 3, 4, 5, 5, 5, 3]
print(n.count(5))
print(n.count(3))
print(n.count(2))

Output:

count() function in Python

append() method in Python:

Using this method we can add elements to the list. The items or elements will be added at the end of the list.

Example: append() method (demo12.py)

l=[]
l.append("Ramesh")
l.append("Suresh")
l.append("Naresh")
print(l)

Output: append() method in Python

insert() method in Python:

We can add elements to the list object by using insert() method. The insert() method takes two arguments as input: one is the index and the other is the element. It will add the elements to the list at the specified index.

Example: insert() method (demo13.py)

n=[10, 20, 30, 40, 50]
n.insert(0, 76)
print(n)

Output: insert() method in Python

Difference between append and insert in Python

Both the methods are used to add elements to the list. But the difference between them is that the append will add the elements to the last, whereas the insert will add the elements at the specified index mentioned.

While you are using insert() method,

  1. If the specified index is greater than max index, then element will be inserted at last position.
  2. If the specified index is smaller than min index, then element will be inserted at first position.

Example: insert() method (demo14.py)

l=[10, 20, 30, 40]
print(l) # [10, 20, 30, 40]
l.insert(1, 111)
print(l) # [10, 111, 20, 30, 40]
l.insert(-1, 222)
print(l) # [10, 111, 20, 30, 222, 40]
l.insert(10, 333)
print(l) # [10, 111, 20, 30, 222, 40, 333]
l.insert(-10, 444)
print(l) # [444, 10, 111, 20, 30, 222, 40, 333]

Output:

Difference between append and insert in Python

extend() method in Python:

Using this method the items in one list can be added to the other.

Example: extend() method (demo15.py)

l1 = [1,2,3]
l2 = ['Rahul', 'Rakesh', 'Regina']

print('Before extend l1 is:', l1)
print('Before extend l2 is:', l2)
l2.extend(l1)
print('After extend l1 is:', l1)
print('After extend l2 is:', l2)

Output:

extend() method in Python

Example: extend() method (demo16.py)
august_txns = [100, 200, 500, 600, 400, 500, 900]
sept_txns = [111, 222, 333, 600, 790, 100, 200]
print("August month transactions are : ",august_txns)
print("September month transactions are : ",sept_txns)
sept_txns.extend(august_txns)
print("August and Sept total transactions amount: ",sum(sept_txns))

Output:

Lists in Python in Detail with Examples

remove() method in Python:

We can use this method to remove specific items from the list.

Example: remove() method (demo17.py)

n=[1, 2, 3]
n.remove(1)
print(n)

Output: remove() method in Python

If the item exists multiple times, then only the first occurrence will be removed. If the specified item not present in list, then we will get ValueError. Before removing elements it’s a good approach to check if the element exists or not to avoid errors.

Example: remove() method (demo18.py)
n=[1, 2, 3, 1]
n.remove(1)
print(n)

Output: 

Example: remove() method (demo19.py)
n=[1, 2, 3, 1]
n.remove(10)
print(n)

Output: Lists in Python

pop() method in Python:

This method takes an index as an argument and removes and returns the element present at the given index. If no index is given, then the last item is removed and returned by default. If the provided index is not in the range, then IndexError is thrown.

Example: pop() method (demo20.py)

n=[1, 2, 3, 4, 5]
print(n.pop(1))
print(n)

print(n.pop())
print(n)

Output:

pop() method in Python

Example: pop() method (demo21.py)

n=[1, 2, 3, 4, 5]
print(n.pop(10))

Output: Lists in Python with Examples

Difference between remove() and pop()

Difference between remove() and pop()

Ordering the elements in list:

reverse() method in python:

This method reverses the order of list elements.

Example: reverse() method (demo22.py)

n=[1, 2, 3, 4, 'two']
print(n)
n.reverse()
print(n)

Output:

reverse() method in python

sort() method in Python:

In a list by default insertion order is preserved. If we want to sort the elements of the list according to default natural sorting order then we should go for sort() method. For numbers the default natural sorting order is ascending order. For strings the default natural sorting order is alphabetical order. To use sort() method, list should contain only homogeneous elements, otherwise we will get TypeError.

Example: sort() method (demo23.py)

n=[1, 4, 5, 2, 3]
n.sort()
print(n)
s=['Suresh', 'Ramesh', 'Arjun']
s.sort()
print(s)

Output:

sort() method in Python

Example: sort() method (demo24.py)
n=[1, 4, 5, 2, 3, 'Suresh', 'Ramesh', 'Arjun']
n.sort()
print(n)

Output: sort() method in Python lists

LIST ALIASING and CLONING in PYTHON:

Aliasing List in Python:

The process of giving a new name to an existing one is called aliasing. The new name is called an alias name. Both names will refer to the same memory location. If we do any modifications on the data, then it will be updated at the memory location. Since both the actual and alias name refer to the same location, any modifications done on an existing object will be reflected in the new one also.

Example: aliasing (demo25.py)

x=[10, 20, 30]
y=x
print(x)
print(y)
print(id(x))
print(id(y))

x[1] = 99
print(x)
print(y)
print(id(x))
print(id(y))

Output:

Aliasing List in Python

Cloning in List:

The process of creating duplicate independent objects is called cloning. We can implement cloning by using slice operator or by using copy() method. These processes create a duplicate of the existing one at a different memory location. Therefore, the both objects will be independent, and applying any modifications on one will not impact the other.

Example: Cloning using slicing operator (demo26.py)

x=[10, 20, 30]
y=x[:]
print(x)
print(y)
print(id(x))
print(id(y))

x[1] = 99
print(x)
print(y)
print(id(x))
print(id(y))

Output:

Cloning in List

Example: Cloning by using copy() method (demo27.py)
x=[10, 20, 30]
y=x.copy()
print(x)
print(y)

print(id(x))
print(id(y))

Output:

Cloning by using copy() method

MATHEMATICAL OPERATORS on LIST

Concatenation operator (+): “+” operator concatenates two list objects to join them and returns a single list. For this, both the operands should be list type, else we will get TypeError

Example: Concatenation (demo28.py)

a= [1, 2, 3]
b= [4, 5, 6]
c = a + b
print(c)

Output: MATHEMATICAL OPERATORS on LIST

Example: TypeError (demo29.py)
a= [1, 2, 3]
b= 'Balu'
c = a + b
print(c)

Output: Lists in Python with Examples

Multiplication operator in Lists:

The “*” operator works to repeat elements in the list by the said number of times. For this one operand should be list and the other operand should be integer, else we get TypeError

Example: Multiplication operator (demo30.py)

a = [1, 2, 3]
print(a)
print(2*a)

Output:

Multiplication operator in Lists

COMPARISON of LISTS in Python

We can use relational operators (<, <=,>,>=) on the List objects for comparing two lists. Initially the first two items are compared, and if they are not the same then the corresponding result is returned. If they are equal, the next two items are compared, and so on

Example: Comparison Operators (demo31.py)

print([1, 2, 3] < [2, 2, 3])
print([1, 2, 3] < [1, 2, 3])
print([1, 2, 3] <= [1, 2, 3])
print([1, 2, 3] < [1, 2, 4])
print([1, 2, 3] < [0, 2, 3])
print([1, 2, 3] == [1, 2, 3])

Output:

COMPARISON of LISTS in Python

While comparing lists which are loaded with strings the following things are considered for the comparison.

  1. The number of elements
  2. The order of elements
  3. The content of elements (case sensitive)
Example: Comparison of lists (demo32.py)
x =["abc", "def", "ghi"]
y =["abc", "def", "ghi"]
z =["ABC", "DEF", "GHI"]
a =["abc", "def", "ghi", "jkl"]

print(x==y)
print(x==z)
print(x==a)

Output:

Comparison of lists

MEMBERSHIP OPERATORS IN LIST

We can check if the element is a member of a list or not by using membership operators. They are:

  1. in operator
  2. not in operator

If the element is a member of list, then the in operator returns True otherwise False. If the element is not in the list, then not in operator returns True otherwise False.

Example: Membership operators (demo33.py)

x=[10, 20, 30, 40, 50]
print(20 in x) # True
print(20 not in x) # False
print(90 in x) # False
print(90 not in x) # True

Output:

MEMBERSHIP OPERATORS IN LIST

NESTED LISTS in Python:

A list within another list is called a nested list. It is possible to take a list as an element in another list. Let’s understand it with example.

Example: Nested Lists (demo34.py)

a = [80, 90]
b = [10, 20, 30, a]
print(b[0])
print(b[1])
print(b[2])
print(b[3])

Output:

NESTED LISTS in Python

LIST COMPREHENSIONS IN PYTHON:

List comprehensions are the precise way of creating a list using iterable objects like tuples, strings, lists etc. Generally, for multiplying each element of a list with 2, we take a for loop and taking one item at a time, multiply it with 2 and finally save the value in a new list.

Example: Multiplying with 2 (demo35.py)

x = [1, 2, 3, 4]
y = []
for i in x:
   y.append(i*2)
print(y)

Output: LIST COMPREHENSIONS IN PYTHON

The above code can be written in a single line using list comprehensions.

Example: List Comprehensions (demo36.py)
x = [1, 2, 3, 4]
y = [ i*2 for i in x]
print(y)

Output: List Comprehensions

Syntax for list comprehension would be

list = [expression for item1 in iterable1 if statement]

Here Iterable represents a list, set, tuple, dictionary or range object. The result of list comprehension is a new list based on the applying conditions.

Example: List Comprehensions (demo37.py)
s=range(1, 20, 3)
for i in s:  #This loop is for knowing what is in s
   print(i)
m=[x for x in s if x%2==0] #List comprehension
print(m)

Output:

Lists in Python with Examples

In the next article, I am going to discuss Tuples in Python. Here, in this article, I try to explain Lists in Python. I hope you enjoy this Lists in Python article. I would like to have your feedback. Please post your feedback, question, or comments about this article.

Leave a Reply

Your email address will not be published. Required fields are marked *