How to create a list in Python?

This article explains how to create a list object in Python.

Creating a list using square brackets- []

We can create a list object using square brackets, i.e. []. For example, to create a list of integers, just enclose them in square brackets. Like this,

list_of_ints = [11, 13, 26, 90, 5, 22, 56]

print(list_of_ints)

Output:

[11, 13, 26, 90, 5, 22, 56]

We created a list of 7 integers.

Creating a list using list constructor

We can also call the list class constructor to create a list object with pre-defined values i.e.

list_of_ints = list( (11, 13, 26, 90, 5) )

print(list_of_ints)

Output:

[11, 13, 26, 90, 5]

We created a list of 5 integers.

Let’s see some examples where we will create different types of list-objects.

Creating a list of strings

# List of strings
list_of_names = ['John', 'Mark', 'Jose', 'Shan', 'Ritika', 'Aadi']

print(list_of_names)

Output:

['John', 'Mark', 'Jose', 'Shan', 'Ritika', 'Aadi']

Creating a list of mixed data types

# List of mixed data types
user_data = ['John', 30, 25.67, 'London']

print(user_data)

Output:

['John', 30, 25.67, 'London']

Creating a list using range() function

Suppose we want to create a list containing numbers in a range (a1 to a2), such as 100 to 110. We can do that using the range() function. In the range() function, we need to pass start, end, and step size i.e.

range(start, end, step=1)

Arguments:

  • start (optional argument). An integer and starting point of the range. Default is 0
  • stop (Required). An integer that represents the end of range. The stop number will not be included in the returned range.
  • step (Optional argument). An integer that represents the incrementation i.e step size. Default is 1.

It returns a sequence of numbers from start to stop-1 and will use the step as the difference between the numbers.

Let’s see some examples,

Create a list of numbers from 100 to 110 with default step size 1,

# Create a list of numbers from 100 to 110
list_of_nums = list(range(100, 111))

print(list_of_nums)

Output:

[100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110]

It creates a list of numbers from 100 to 110.

Create a list of numbers from 10 to 30 with default step size 2,

# Create a list of numbers from 10 to 20 with step size 2
list_of_nums = list(range(10, 30, 2))

print(list_of_nums)

Output:

[10, 12, 14, 16, 18, 20, 22, 24, 26, 28]

It creates a list of numbers from 10 to 30 with a step size of 2.

Summary:

Today we learned how to create a list in python.

That’s all for this article. In the following article, we will learn more about list usage and operations.

Advertisements

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top