How To Create A List In Python

In this tutorial, we will learn how to create a list in Python. A list is a data structure that can store multiple items in a single variable. It is an ordered collection of elements, which can be of different types, such as integers, strings, or even other lists. It is one of the most commonly used data structures in Python and is very useful in various programming scenarios.

Step 1: Creating an Empty List

There are two ways to create an empty list in Python:

  1. Using square brackets
  2. Using the list() constructor

Here is an example of each:

Both empty_list1 and empty_list2 will be empty lists.

Step 2: Creating a List with Elements

To create a list with elements, you can either use square brackets and separate the elements with commas or use the list() constructor with an iterable (e.g. a string or a tuple) as the argument.

Here is an example of each:

Step 3: Adding Elements to a List

To add elements to a list, you can use the following methods:

  1. append() – Adds an element at the end of the list
  2. insert() – Adds an element at the specified position
  3. extend() – Adds the elements of an iterable (e.g. another list, a tuple, or a string) to the end of the list

Here is an example of each:

Output:

['apple', 'banana', 'cherry', 'orange']
['apple', 'grape', 'banana', 'cherry', 'orange']
['apple', 'grape', 'banana', 'cherry', 'orange', 'kiwi', 'melon']

Step 4: Removing Elements from a List

To remove elements from a list, you can use the following methods:

  1. remove() – Removes the first occurrence of a specified element
  2. pop() – Removes the element at the specified index, or the last element if no index is specified
  3. clear() – Removes all elements from the list

Here is an example of each:

Output:

['apple', 'cherry', 'orange']
['apple', 'orange']
[]

Step 5: Accessing Elements in a List

You can access elements in a list by their index, with the first element having an index of 0. You can also use negative indexing to access elements from the end of the list, with -1 being the last element’s index.

Here is an example:

Output:

apple
orange
['apple', 'grape', 'cherry', 'orange']

Full Code:

Conclusion

In this tutorial, we learned how to create a list in Python, add and remove elements, and access elements in the list. Lists are an essential data structure that can be used in various programming scenarios and are an important part of the Python language.