Python Creating and Accessing List

How do you create an empty list in Python?

To create an empty list in Python, you can use either of the following methods:

Using square brackets:

Python
my_list = []

Using the list() constructor:

Python
my_list = list()

Both of these methods will create an empty list named my_list that does not contain any elements.


Create a list containing the elements: 1, 2, 3, 4, 5.

Here is a Python code to create a list containing the elements 1, 2, 3, 4, and 5:

Python
my_list = [1, 2, 3, 4, 5]

Now, my_list is a list containing the elements 1, 2, 3, 4, and 5.


Access the third element of the list you created.

To access the third element of the list my_list, which we created earlier, you can use index 2 since indexing starts from 0 in Python.

Here’s how you do it:

Python
third_element = my_list[2]

This will assign the value 3 (which is the third element) to the variable.