This concise, practical article walks you through a couple of different ways to create a list in Python 3.
Using square brackets
This approach is often used to create a list with predefined elements. What you need to do is to enclose the elements in a pair of square brackets and separate them with commas.
Example:
# Creating a list of numbers
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
# Creating a list of strings
fruits = ["Dog", "Cat", "Turtle", "Dolphin"]
# Creating a list of mixed data types
mixed = [2024, "Sling Academy", 3.0, True]
Using the list() function
If you want to create a list from an existing iterable, such as a string or tuple, then using the list()
function is the best choice.
Example:
# Creating a list from a string
word = "Sling Academy"
characters = list(word)
print(characters)
# Creating a list from a tuple
tuple_numbers = (1, 2, 3, 4, 5)
number_list = list(tuple_numbers)
print(number_list)
Output:
['S', 'l', 'i', 'n', 'g', ' ', 'A', 'c', 'a', 'd', 'e', 'm', 'y']
[1, 2, 3, 4, 5]
Using list comprehension
The main points are:
- Define the logic or transformation for generating list elements inside square brackets.
- Separate the logic or transformation with a for loop or conditional statements if needed.
- Assign the list comprehension to a variable.
Example:
# Creating a list of squared numbers
squared = [x**2 for x in range(1, 6)]
print(squared)
# Creating a list of even numbers from 1 to 10
evens = [x for x in range(1, 11) if x % 2 == 0]
print(evens)
Output:
1, 4, 9, 16, 25]
[2, 4, 6, 8, 10]
This approach is flexible but might be tough for programmers who are new to Python.
Initializing an empty list and adding elements later
You can create an empty list then call the append() method to dynamically add
elements to the list.
Example:
# Creating an empty list
my_list = []
# Appending elements to the list
my_list.append("Sling Academy")
my_list.append("Python")
my_list.append("Programming")
print(my_list)
Output:
['Sling Academy', 'Python', 'Programming']
That’s it.