We will discuss the basics of lists in Python, from creation and manipulation to the various operations which can be performed on them. The list data structure is an ordered collection of items that provides efficient access and manipulation of individual elements.
Table of contents
1. What is a List in Python?
Python list is an ordered collection of items that can contain elements of any data type, including other lists. It is a mutable data structure, meaning its contents can be modified after they have been created. In Python, Lists are typically used to store data that needs to be sorted, searched, or altered in some way. They can also be used to perform operations on a set of data quickly.
1.1 Example of List in Python
Following is a quick example of a list.
# Create a list of numbers
my_list = [1, 2, 3, 4]
# Create a list of mixed datatypes
my_list = [1, 'Hello', [1,2,3]]
1.2 Key Points of List
Following are some key points about the python list.
- Lists are mutable, meaning their contents can be modified after they have been created.
- Elements in a list can be accessed by their index.
- A list is an ordered collection of elements.
- Lists can contain elements of any data type, including other lists.
2. Create a List in Python
There are several different ways to create a list in Python. The most common is to use square brackets []
to enclose a comma-separated list of elements.
2.1 list() – Create a List
The list()
function takes in an iterable object and creates a list from it. This means that any object which can be iterated over (for example, a string, a tuple, or a range) can be used to create a list.
It is a convenient way to quickly create lists, as it requires no additional code. It can also be used to convert tuples and ranges into lists, which can be useful when working with such objects.
# Creates a list from string
my_list = list('Hello')
print(my_list)
# Creates a list using range()
my_list = list(range(1, 5))
print(my_list)
# Creates a list from tuple
my_list = list((1, 2, 3))
print(my_list)
Yields below output.

To create an empty list, just use either empty square brackets [] or list().
2.2 Create Lists using List Comprehension
Python List Comprehension allows you to create a new list by applying an operation to each element in an existing iterable. List comprehensions are a concise, readable way to create new lists, and are often preferred over using a for loop and the append()
method.
For example, you can create a list of the squares of the numbers from 0 to 9 like this:
# List Comprehension
squares = [x**2 for x in range(10)]
List comprehension can be more memory-consuming when working with large datasets and it is not a good idea to use them for large datasets.
2.3 Create a Nested List
A nested list is a list that contains other lists as its elements. They are a versatile data structure that allows you to store a collection of lists within a single list in python.
# Create nested list
nested_list = [
['Python', 'Java', 'C++'],
['JavaScript', 'TypeScript',
'Rust'],
['Go', 'Kotlin', 'Swift']
]
3. Accessing Elements in a List
In Python, list elements are indexed starting from 0, so the first element in a list has an index of 0, the second element has an index of 1, and so on.
# Get element from list by index
my_list = ['Python', 'Java', 'C++', 'JavaScript']
print(my_list[0])
# Output:
# 'Python'
To access elements at the end of the list, you can use negative indexing, in which -1 represents the last element, -2 represents the second last, and so on.
last_element= my_list[-1]
print(last_element)
# Output
# 'Javascript'
3.1 Access the Elements of a Nested List
In order to access the elements of a nested list, you need to use multiple sets of square brackets, with the first set referencing the outer list and the subsequent sets referencing the inner lists.
# Create nested list
nested_list = [ ['Python', 'Java', 'C++'],
['JavaScript', 'TypeScript', 'Rust'],
['Go', 'Kotlin', 'Swift']
]
# Index 0 of the outer list and Index 1 of the Inner list
print(nested_list[0][1])
# Output:
# Java
4. Different Data Types Allowed in a List
A single Python list can contain elements of different data types, such as integers, strings, floats, booleans, and even other lists or other complex data types like tuples or objects of custom classes.
# A list of integers
numbers = [1, 2, 3, 4, 5]
# A list of strings
words = ['hello', 'world', 'foo', 'bar']
# A list of booleans
flags = [True, False, True, False, True]
# A list of mixed data types
mixed_list = [1, 'hello', 3.14, True, [1, 2, 3]]
# A list of lists
nested_list = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
5. Perform for Loop on a List
You might have seen that the most common way to iterate over a list in Python is by using a for
loop.
5.1 Syntax of for loop on a list
for item in my_list:
# Code to be executed for each item
5.2 Example of for loop on a List
Here is an example of how to use the for loop on a list in python.
# For loop example to iterate list
languages = ['Python','Java','C++','JavaScript']
for language in languages:
print(language)
# Ouput:
# Python
# Java
# C++
# JavaScript
The above example prints each element in the list, but you can do any other operations in the loop as well depending on your use case like adding them to another list, performing some operation on it, and so on.
5.3 enumerate() and FOR Loop on a List
Another way of looping through list elements is by using enumerate()
function which returns both the index and value of the list elements. This method is useful when you want to access index in for loop.
# Iterate list using enumerate
for index, language in enumerate(languages):
print(f'{index+1}. {language}')
# Output
# 1. Python
# 2. Java
# 3. C++
# 4. JavaScript
6. Python List Vs Python Array
Python List is a built-in data structure whereas Arrays are not built-in. To use an array we need to import it using either the python NumPy module or we can use the python array module.
The python array module is built in while the NumPy library is a third party and you need to install it before using it. Here is the main point that makes them unique. Depending on your case you can use any of them.
Property | Python List | Array (Python module) | NumPy Array |
---|---|---|---|
Flexibility | Can store elements of different data types | Can only store elements of the same data type | Can only store elements of the same data type |
Built-in methods | Yes | No | Yes |
Memory efficiency | Lower | Higher | Higher |
Performance | Slower | Faster | Faster |
Built-in mathematical operations | No | No | Yes |
Suitable for | General-purpose use cases | Numerical computations | Numerical computations |
7. Difference Between List and Tuple
In Python, lists and tuples are both used to store collections of items. Many of us don’t see the difference between the two at first glance. There are differences between the python list and python tuple data structure based on the following key points:
Property | Lists | Tuples |
---|---|---|
Mutability | Mutable | Immutable |
Flexibility | Can store elements of different data types | Can only store elements of the same data type |
Built-in methods | Yes | No |
Memory efficiency | Same as lists | Same as lists |
Performance | Same as lists | Same as lists |
Built-in mathematical operations | No | No |
Suitable for | General-purpose use cases, where data may change | Data integrity where data need to remain constant |
8. Different Operations on Python List
We will explore key Operations of lists such as adding, removing, inserting, sorting, and slicing, and how to use them effectively in different scenarios. For a full list refer to Python List Methods.
8.1 Adding Elements to List
You can add new elements to the end of a list using the append()
method. This will add a new element after the last position on the list. Of course, there are other ways to add elements to a list in python.
my_list.append('Rust')
# Output
# ['Python', 'Java', 'C++', 'JavaScript', 'Rust']
8.2 Removing Elements From a List
You can remove elements by index using the pop()
method. By default, it will remove the last element if no index is passed.
my_list.pop(1)
print(my_list)
# Output
# ['Python', 'C++', 'JavaScript']
8.3 Concatenation of two Lists
You can concatenate two lists by using the +
operator or the extend()
method. Look at the following example, This creates a new list that contains all the elements of both list1
and list2
.
list1 = ['Python', 'Java']
list2 = ['C++', 'JavaScript']
new_list = list1 + list2
print(new_list)
# Output
#['Python', 'Java', 'C++', 'JavaScript']
8.4 Sorting a List
You can sort the elements of a list in Python using the sort() method or the built-in sorted() function. You can sort a list either in ascending or descending order.
my_list = [5, 3, 1, 4, 2]
my_list.sort()
print(my_list)
# Output
# [1, 2, 3, 4, 5]
8.5 List Slicing
List slicing in Python is a technique for accessing a range of elements within a list in Python. It allows you to extract a portion of a list by specifying the start index, stop index, and step size of the slice.
Following is the Syntax of List Slicing:
# List slice()
list[start:stop:step]
Where start
is the index of the first element to include, stop
is the index of the first element to exclude, and step
is the number of indices between slice elements.
print(my_list[1:3])
# prints ['Java', 'C++']
print(my_list[:2])
# prints ['Python', 'Java']
print(my_list[2:])
# prints ['C++', 'JavaScript']
print(my_list[::2])
# prints ['Python','C++']
Following are some of the most used Python List Examples
9. Conclusion
In this article, We have explained what is Python List and how to create a python list and nested list. We have also discussed how to perform different operations on the python list. Hopefully, now you have a clear idea of how Python list works. If you still have any queries, just leave them in a comment.
Happy Coding!!!