Python List Explain with Examples

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.

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.

  1. Lists are mutable, meaning their contents can be modified after they have been created.
  2. Elements in a list can be accessed by their index.
  3. A list is an ordered collection of elements.
  4. 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') 

# Creates a list using range()
my_list = list(range(1, 5)) 

# Creates a list from tuple
my_list = list((1, 2, 3)) 

Yields below output.

python lists

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', 
    ['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']

# 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]
# 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

# 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:

# 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.

PropertyPython ListArray (Python module)NumPy Array
FlexibilityCan store elements of different data typesCan only store elements of the same data typeCan only store elements of the same data type
Built-in methodsYesNoYes
Memory efficiencyLowerHigherHigher
Built-in mathematical operationsNoNoYes
Suitable forGeneral-purpose use casesNumerical computationsNumerical computations
Table Explaining the difference between python lists vs python arrays

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:

FlexibilityCan store elements of different data typesCan only store elements of the same data type
Built-in methodsYesNo
Memory efficiencySame as listsSame as lists
PerformanceSame as listsSame as lists
Built-in mathematical operationsNoNo
Suitable forGeneral-purpose use cases, where data may changeData integrity where data need to remain constant
Python List VS Python Tuple

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.

# 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.

# 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
# 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]
# 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()

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.

# prints ['Java', 'C++']

# prints ['Python', 'Java']

# prints ['C++', 'JavaScript']

# 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!!!


I am a software Engineer with extensive 4+ years of experience in Programming related content Creation.

Leave a Reply

You are currently viewing Python List Explain with Examples