# Creating a List in Python

A list is one of the most commonly used data structures in Python. It is capable of storing a collection of ordered and mutable items in a single variable. In this article, we will be discussing how to create lists in Python.

## Basic List Implementation

In Python, lists are created by enclosing a sequence of comma-separated values within square brackets ([]). For example:

``````
fruits = ['apple', 'banana', 'cherry']
numbers = [1, 2, 3, 4, 5]
mixed_list = ['apple', 1, 'banana', 2, 'cherry', 3]
``````

We can access individual elements of a list using their index, which starts from 0. For example, to access the first element of the `fruits` list, we can use `fruits[0]`.

## List with Range Function

To create a list with a series of numbers, we can use the built-in `range()` function. For example:

``````
numbers = list(range(10))
print(numbers)  # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
``````

This code creates a list of numbers that range from 0 to 9. The `list()` constructor is used to create the list from the `range()` function.

## List Comprehension

List comprehension is a powerful feature in Python that allows us to create lists based on certain conditions. It provides a more concise and readable way to create lists. For example:

``````
even_numbers = [x for x in range(10) if x % 2 == 0]
print(even_numbers)  # [0, 2, 4, 6, 8]
``````

In this example, we use list comprehension to create a list of even numbers between 0 and 9 inclusive. The condition `if x % 2 == 0` filters out odd numbers.

## Conclusion

List is a simple and effective way to store data in Python. In this article, we have learned how to create lists in various ways, including basic implementation, range function, and list comprehension. Understanding the fundamentals of lists will help you in writing efficient programs.

Scroll to Top