Using Lists for Storing and Manipulating Data in Python

A list is one of the most fundamental data types in Python. They can hold an arbitrary number of values, which makes them useful when you need to store multiple items in a single variable. In this art …

Updated November 26, 2023

A list is one of the most fundamental data types in Python. They can hold an arbitrary number of values, which makes them useful when you need to store multiple items in a single variable. In this article, we’ll learn how to create a list of integers and how it is used.

Creating a List of Integers: Python allows us to initialize lists with an iterable or directly as elements. Here’s how you can do both:

# Using the range() function to create a list of integers from 1 to 5
list_of_integers = list(range(1, 6))
print(list_of_integers) # Output: [1, 2, 3, 4, 5]

Adding and Removing Elements:

Python lists allow us to add or remove elements using the append() and remove() methods respectively. Let’s demonstrate this:

# Adding an element to a list
list_of_integers.append(6)
print(list_of_integers) # Output: [1, 2, 3, 4, 5, 6]

# Removing an element from the list
list_of_integers.remove(4)
print(list_of_integers) # Output: [1, 2, 3, 5, 6]

Indexing and Slicing:

Lists can be indexed just like strings (with positive numbers being from the start of the list to the end), and sliced using similar syntax:

print(list_of_integers[0]) # Output: 1
print(list_of_integers[-1]) # Output: 6
print(list_of_integers[:3]) # Output: [1, 2, 3]
print(list_of_integers[3:]) # Output: [5, 6]

List Comprehensions and Loops:

Python lists can also be manipulated using list comprehensions or traditional loops. For instance, you could use a loop to double every element in the list:

for i in range(len(list_of_integers)):
    list_of_integers[i] *= 2
print(list_of_integers) # Output: [2, 4, 6, 10, 12, 18]

Manipulating Lists with Methods:

Python provides a host of list methods for common operations. For example, here we’ll use the sorted() method to sort the list in ascending order:

list_of_integers = sorted(list_of_integers)
print(list_of_integers) # Output: [1, 2, 3, 4, 5, 6, 10, 12, 18]

Lists also have a number of operations that can be performed on them with different built-in functions (e.g., min(), max()), and you can use list comprehensions to perform more complex operations:

print(min(list_of_integers)) # Output: 1
print(max(list_of_integers)) # Output: 18
squared_values = [i**2 for i in list_of_integers]
print(squared_values) # Output: [1, 4, 9, 16, 25, 36, 49, 64, 81]
Hey! Do you love Python? Want to learn more about it?
Let's connect on Twitter or LinkedIn. I talk about this stuff all the time!