How to create a list in Python

In this article, you’ll learn how to create a list in Python. A list is a data type that is used to handle multiple elements. I highly recommend you get the “Python Crash Course Book” to learn Python.

Method 1: Use a square bracket

It is very easy to create a list by using square brackets in Python. All the items in a list are separated by commas. The items can be of any data type, such as integer, string, or float.

# Create a list
a = [9, 18, 25, 4.2, 'AI', 33.7]

# Display the list
print(a)

# Display the type
print(type(a))

Output:

[9, 18, 25, 4.2, 'AI', 33.7]
<class 'list'>

Method 2: Use a list keyword

You can also use this method to create a list.

# Use list keyword to initialize the list
a = list((9, 18, 25, 4.2, 'AI', 33.7))

# Display the list
print(a)

# Display the type
print(type(a))

Output:

[9, 18, 25, 4.2, 'AI', 33.7]
<class 'list'>

Create a List of Integers

# list of integers
a = [5, 10, 15, 20]

# Display the list
print(a)

# Display the type
print(type(a))

Output:

[5, 10, 15, 20]
<class 'list'>

Create a List of Strings

# list of strings
a = ['AI', 'ML', 'DL']

# Display the list
print(a)

# Display the type
print(type(a))

Output:

['AI', 'ML', 'DL']
<class 'list'>

Create a List of Floats

# list of float
a = [2.3, 4.8, 5.9, 8.7]

# Display the list
print(a)

# Display the type
print(type(a))

Output:

[2.3, 4.8, 5.9, 8.7]
<class 'list'>

Create an Empty list

# Create an empty list
a = []

# Display the list
print(a)

# Display the type
print(type(a))

Output:

[]
<class 'list'>

Create a Nested List

The item in a list can be another list. This is called a nested list.

# Nested list
a = [[5, 6.8, 'ML', 88], 'AiHints', ['Hello']]

# Display the list
print(a)

# Display the type
print(type(a))

Output:

[[5, 6.8, 'ML', 88], 'AiHints', ['Hello']]
<class 'list'>

Leave a Comment

Your email address will not be published.