How to make a list in Python
Create powerful lists in Python using example code: learn how to store data, access elements, and more.
Creating a List in Python
Python lists can be created in various ways. The simplest way is to enclose the elements in square brackets, separated by commas. For example, a list of numbers from 1 to 5 can be created as follows:
list_of_numbers = [1, 2, 3, 4, 5]
Another way to create a list is to use the list()
constructor, which takes an iterable object as an argument and returns a list object. For example, to create a list of numbers from 1 to 5 using the list()
constructor, we can call it as follows:
list_of_numbers = list(range(1, 6))
We can also create a list from a string by splitting it into a list of characters. For example, to create a list of characters from the string "Hello"
, we can call the list()
constructor as follows:
list_of_characters = list("Hello")
Finally, we can use list comprehension to create a list based on a certain condition. For example, to create a list of even numbers from 1 to 10, we can use the following code:
list_of_even_numbers = [x for x in range(1, 11) if x % 2 == 0]
These are some of the ways to create lists in Python. For more information, refer to the official Python documentation.