Back to: Python Tutorials For Beginners and Professionals
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.
- Python Data structures
- Sequence of elements
- What is List in Python
- Creating list
- Difference between list() function and list class
- Mutability
- Accessing elements in the list
- Important functions and methods in the list
- Difference between append and insert
- Difference between remove() and pop() methods
- Ordering elements of List:
- Aliasing and Cloning of list objects
- Mathematical + and * operators
- Comparison of lists
- Membership operators
- Nested Lists
- List comprehensions
Python Data Structures:
In python, there are quite a few data structures available. They are used to store a group of individual objects as a single entity.
Sequences
Sequences are those, which contain 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 that can store a group of elements or objects. It has the following features/properties:
- Lists can store the same type as well as different types of elements. Hence, it is heterogeneous.
- 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.
- Insertion order is preserved. The order, in which the items are added to a list, is the order in which output is displayed.
- The list can store duplicates elements.
- In lists, the index plays the main role. Using index we perform almost all the operations on the items in it.
- 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:
Example: Creating a list with elements (demo2.py)
names = ["Mohan", "Prasad", "Ramesh", "Mohan", 10, 20, True, None] print(names)
Output:
You can observe from the output that the order is preserved and also duplicate items are allowed. It can contain mixed data types (strings, integers, boolean, None) elements.
Creating a list in Python by using the list() function
You can create a list by using the 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:
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. The list is a 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:
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:
Accessing List in Python:
There are three ways in which you can access the elements in the list in python. They are:
- By using indexing
- By using the slicing operator
- By using loops
Accessing List By using indexing in Python:
This way is the same as we have seen for the 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. The positive index represents from left to right direction and the negative index represents from right to left direction.
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:
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:
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, the default value is 0. stop represents the end index where the 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 the 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 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:
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:
IMPORTANT FUNCTIONS OR METHODS OF LISTS IN PYTHON
In python, a method and functions 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 to 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 a 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:
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:
insert() method in Python:
We can add elements to the list object by using the 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:
Difference between append and insert in Python
Both 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 the insert() method,
- If the specified index is greater than the max index, then the element will be inserted at the last position.
- If the specified index is smaller than the min index, then the element will be inserted at the 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:
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:
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:
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:
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:
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:
Example: pop() method (demo21.py)
n=[1, 2, 3, 4, 5] print(n.pop(10))
Output:
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:
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 the default natural sorting order then we should go for the sort() method. For numbers, the default natural sorting order is ascending order. For strings, the default natural sorting order is alphabetical order. To use the sort() method, the 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:
Example: sort() method (demo24.py)
n=[1, 4, 5, 2, 3, 'Suresh', 'Ramesh', 'Arjun'] n.sort() print(n)
Output:
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 to 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:
Cloning in List:
The process of creating duplicate independent objects is called cloning. We can implement cloning by using the slice operator or by using the copy() method. These processes create a duplicate of the existing one at a different memory location. Therefore, both objects will be independent, and applying any modifications to 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:
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:
MATHEMATICAL OPERATORS on LIST
The 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:
Example: TypeError (demo29.py)
a= [1, 2, 3] b= 'Balu' c = a + b print(c)
Output:
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 an integer, else we get TypeError
Example: Multiplication operator (demo30.py)
a = [1, 2, 3] print(a) print(2*a)
Output:
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:
While comparing lists that are loaded with strings the following things are considered for the comparison.
- The number of elements
- The order of elements
- 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:
MEMBERSHIP OPERATORS IN LIST
We can check if the element is a member of a list or not by using membership operators. They are:
- in operator
- not in operator
If the element is a member of the 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:
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:
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:
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:
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:
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.