Hey! If you love Python and building Python apps as much as I do, let's connect on Twitter or LinkedIn. I talk about this stuff all the time!

Creating Lists of Numbers in Python

Learn how to create lists of numbers in Python with this comprehensive guide. Get started today and become proficient in creating numerical lists. …


Updated May 30, 2023

Learn how to create lists of numbers in Python with this comprehensive guide. Get started today and become proficient in creating numerical lists.

How to Create a List of Numbers in Python

Definition of the Concept


In Python, a list is a collection of items that can be of any data type, including strings, integers, floats, and more. A list of numbers specifically refers to a collection of numeric values, such as integers or floats.

Step-by-Step Explanation


Creating a list of numbers in Python involves two primary methods: using square brackets [] and the list() function. We will explore both methods in detail below.

Method 1: Using Square Brackets []

To create a list of numbers using square brackets, follow these steps:

Step 1: Define Your List


numbers = []

In this example, we have defined an empty list called numbers.

Step 2: Append Numbers to the List

numbers.append(10)
numbers.append(20)
numbers.append(30)

Here, we append three numbers (10, 20, and 30) to our numbers list.

Method 2: Using the list() Function

Alternatively, you can use the list() function to create a list of numbers. Here’s how:

Step 1: Define Your List


numbers = list()

This creates an empty list called numbers.

Step 2: Pass Numbers to the list() Function


numbers = [10, 20, 30]

By passing a sequence of numbers (10, 20, and 30) directly to the list() function, we create our desired list.

Code Explanation


In both methods, the square brackets [] are used to define a list. When using the append() method, each number is added as an individual element within the list. In contrast, passing numbers directly to the list() function creates a single list with all numbers as elements.

Example Use Cases


Here’s how you can use your newly created list of numbers in various scenarios:

Printing the List

print(numbers)
# Output: [10, 20, 30]

Accessing Specific Elements

print(numbers[0])  # Output: 10
print(numbers[1])  # Output: 20
print(numbers[2])  # Output: 30

Modifying the List

numbers.append(40)
print(numbers)  # Output: [10, 20, 30, 40]

In conclusion, creating a list of numbers in Python is a straightforward process using either square brackets [] or the list() function. With this guide, you’re now equipped to create numerical lists and perform various operations on them.


How to Create a List of Numbers in Python: A Step-by-Step Guide for Beginners

Learn how to create lists of numbers in Python with this comprehensive guide. Get started today and become proficient in creating numerical lists.

Stay up to date on the latest in Python, AI, and Data Science

Intuit Mailchimp