Skip to content

Creating Lists in Python - A Comprehensive Guide

Updated: at 02:01 AM

Lists are one of the most commonly used data structures in Python. They allow you to store multiple elements or items in a single variable. Lists are very flexible and have many built-in methods that allow you to modify them and manipulate their data easily.

In this comprehensive guide, you will learn everything you need to know about creating, initializing, and manipulating lists in Python.

Table of Contents

Open Table of Contents

Introduction to Lists

In Python, a list is an ordered sequence of elements. Unlike arrays in other languages, Python lists are dynamic in size. This means you don’t need to specify how many elements a list will hold when creating it.

Lists elements can be of any Python data type, including integers, floats, strings, booleans, and even other lists. Lists can also contain a combination of different data types.

Lists are defined and created using square brackets [] with elements separated by commas. For example:

primes = [2, 3, 5, 7, 11, 13]
fruits = ['apple', 'banana', 'mango', 'strawberry']

The key advantages that lists provide are:

Let’s look at how to create lists in Python in detail.

Creating Lists

Lists can be created in Python by two methods:

  1. Using square brackets
  2. List comprehensions

Using Square Brackets

This is the standard method of creating lists in Python.

To create an empty list, just use a pair of square brackets with nothing inside:

empty_list = []

To create a list with initial elements, put the element values inside the square brackets separated by commas:

numbers = [1, 2, 3]
fruits = ['apple', 'mango', 'banana']

You can create lists with different data types together:

mixed_list = [1, 'hello', 3.4, True]

Elements can be added to the lists later as well. Lists are mutable, meaning their elements can be changed after creation.

For example:

# Create empty list
nums = []

# Add elements
nums.append(1)
nums.append(2)
nums.append(3)

print(nums)

# Output: [1, 2, 3]

List Comprehensions

List comprehensions provide a concise way to create lists using a descriptive formula rather than procedural code.

The basic syntax of a list comprehension is:

[expression for item in iterable]

This generates a new list by applying the expression to each item in the iterable.

For example, to create a list of squares:

squares = [x**2 for x in range(10)]

print(squares)

# Output: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

List comprehensions can also contain optional if conditional statements to filter elements:

even_squares = [x**2 for x in range(10) if x % 2 == 0]

print(even_squares)

# Output: [0, 4, 16, 36, 64]

Multiple for loops can be nested to iterate over multiple iterables:

all_combos = [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]

print(all_combos)

# Output: [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]

List comprehensions provide a faster and more concise way to create lists as compared to procedural approaches using for loops and append().

Accessing and Modifying List Elements

Elements in a list can be accessed by their index. Indices start from 0 for the first element and go up to n-1 for the last element in a list with n elements.

fruits = ['apple', 'banana', 'mango']

print(fruits[0]) # apple
print(fruits[1]) # banana
print(fruits[2]) # mango

List elements can be modified by directly changing the value at a particular index:

fruits[1] = 'kiwi'

print(fruits) # ['apple', 'kiwi', 'mango']

Trying to access an index outside the bounds of the list will result in an IndexError.

Elements can be added to the end of the list using the append() method:

fruits.append('strawberry')

print(fruits) # ['apple', 'kiwi', 'mango', 'strawberry']

There are many other methods that can be used to modify lists like insert(), remove(), pop(), etc. These will be covered in detail later.

Built-in List Methods

Python contains many built-in methods that you can apply directly to lists to manipulate them and access their elements.

Here we will cover the most commonly used list methods with examples.

Append

The append() method adds a single element to the end of the list.

Syntax:

list.append(element)

Example:

fruits = ['apple', 'banana']
fruits.append('mango')

print(fruits) # ['apple', 'banana', 'mango']

Extend

The extend() method appends multiple elements to the end of the list.

Instead of a single element, it takes an iterable object like list, tuple, set etc. and appends all the elements.

Syntax:

list.extend(iterable)

Example:

fruits = ['apple', 'banana']
fruits.extend(['mango', 'kiwi'])

print(fruits) # ['apple', 'banana', 'mango', 'kiwi']

Insert

The insert() method inserts an element at a specified index in the list.

Syntax:

list.insert(index, element)

Example:

fruits = ['apple', 'banana']
fruits.insert(1, 'mango')

print(fruits) # ['apple', 'mango', 'banana']

Remove

The remove() method removes the first occurrence of a specified element from the list.

Syntax:

list.remove(element)

Example:

fruits = ['apple', 'mango', 'banana']
fruits.remove('mango')

print(fruits) # ['apple', 'banana']

If the element does not exist in the list, a ValueError is raised.

Pop

The pop() method removes and returns the element at the given index.

Syntax:

list.pop(index)

If no index is specified, it removes and returns the last element.

Example:

fruits = ['apple', 'mango', 'banana']

popped_item = fruits.pop(1)

print(fruits)      # ['apple', 'banana']
print(popped_item) # mango

Clear

The clear() method removes all the elements from the list, making it empty.

Syntax:

list.clear()

Example:

fruits = ['apple', 'mango', 'banana']
fruits.clear()

print(fruits) # []

Index

The index() method returns the index of the first occurrence of an element in the list.

Syntax:

list.index(element)

Example:

fruits = ['apple', 'mango', 'banana']
pos = fruits.index('mango')

print(pos) # 1

If the element is not found, a ValueError is raised.

Count

The count() method returns the number of occurrences of an element in the list.

Syntax:

list.count(element)

Example:

numbers = [1, 2, 3, 4, 1, 2, 1]
count = numbers.count(1)

print(count) # 3

Sort

The sort() method sorts the list in ascending order by default.

Syntax:

list.sort()

To sort in descending order:

list.sort(reverse=True)

Example:

numbers = [4, 1, 2, 3]
numbers.sort()

print(numbers) # [1, 2, 3, 4]

numbers.sort(reverse=True)

print(numbers) # [4, 3, 2, 1]

The sorted() built-in function can also be used to sort a list while keeping the original list unchanged:

numbers = [4, 1, 2, 3]
new_list = sorted(numbers)

print(numbers) # [4, 1, 2, 3]
print(new_list) # [1, 2, 3, 4]

Reverse

The reverse() method reverses the order of elements in the list.

Syntax:

list.reverse()

Example:

numbers = [1, 2, 3, 4]
numbers.reverse()

print(numbers) # [4, 3, 2, 1]

Copy

The copy() method returns a shallow copy of the list.

Syntax:

new_list = list.copy()

Example:

fruits = ['apple', 'mango', 'banana']
new_fruits = fruits.copy()

print(new_fruits) # ['apple', 'mango', 'banana']

The original list is not modified. This is in contrast with the = operator which copies the reference and any changes made to the copy will reflect in the original list as well.

Copying Lists

Since lists are mutable, modifying them in-place changes the original object. To prevent unintended side effects, copies of the original list are often created.

There are a few ways to copy lists in Python:

1. list.copy()

This creates a shallow copy of the list. The nested objects inside (like dicts, lists etc.) are not copied and still reference the originals.

original = [[1, 2], [3, 4]]
copy = original.copy()

copy[0][0] = 0
print(original) # [[0, 2], [3, 4]] Modified

2. list[:]

Slicing the entire list creates a shallow copy as well:

original = [1, 2, 3]
copy = original[:]

copy[0] = 0
print(original) # [1, 2, 3] Unchanged

3. list(list)

Typecasting into a list also creates a shallow copy:

original = [1, 2, 3]
copy = list(original)

copy[0] = 0
print(original) # [1, 2, 3] Unchanged

4. deepcopy()

The deepcopy() function from the copy module creates a deep copy of the list and any nested objects, recursively.

from copy import deepcopy

original = [[1, 2], [3, 4]]
copy = deepcopy(original)

copy[0][0] = 0
print(original) # [[1, 2], [3, 4]] Unchanged

Deepcopy should be used if a fully independent clone is required.

Joining and Splitting Lists

Multiple lists can be combined into a single list using the + operator:

list1 = [1, 2]
list2 = [3, 4]

joined_list = list1 + list2
print(joined_list) # [1, 2, 3, 4]

An iterable like string, tuple etc. can be splitted into a list using list() typecasting:

string = 'python'
list_from_string = list(string)
print(list_from_string) # ['p', 'y', 't', 'h', 'o', 'n']

The split() string method is another way to split strings using a delimiter:

string = 'python,programming,language'
split_list = string.split(',')
print(split_list) # ['python', 'programming', 'language']

Iterating Through Lists

We can loop over the elements in a list using a for loop and access each item sequentially.

Syntax:

for item in list:
  # do something with item

Example:

numbers = [1, 2, 3]

for num in numbers:
  print(num)

# Output:
# 1
# 2
# 3

We can also retrieve both the index and item value using the enumerate() method:

colors = ['red', 'green', 'blue']

for index, color in enumerate(colors):
  print(index, color)

# Output:
# 0 red
# 1 green
# 2 blue

While looping, we can break out of the loop using break and use continue to skip to the next iteration.

List Comprehensions

List comprehensions provide a concise way to create lists using the following syntax:

[expr for val in collection]

Any operations that map the val to an expr are applied to each element in collection to construct the new list.

For example:

squares = [x**2 for x in range(10)]
print(squares)
# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

even = [x for x in range(10) if x%2==0]
print(even)
# [0, 2, 4, 6, 8]

List comprehensions are faster than procedural code using loops and append(). They also provide a more concise way to code.

Multiple for loops can be cascaded for nested iterations.

Example:

matrix = [[1, 2], [3,4], [5,6]]
flattened = [num for row in matrix for num in row]

print(flattened)
# [1, 2, 3, 4, 5, 6]

Multidimensional Lists

In Python, lists can contain other lists as elements to create multidimensional lists (nested lists).

For example:

matrix = [[1, 2, 3], [4, 5, 6]]

This matrix has 2 rows and 3 columns.

Individual elements can be accessed using nested index lookups:

print(matrix[0][1]) # 2
print(matrix[1][2]) # 6

Nested lists provide a flexible way to represent multidimensional data.

The nested lists don’t have to be regular matrices. The inner lists can be different lengths:

irregular_list = [[1, 2], [3, 4, 5]]

Operations like appending new lists can be used to grow multidimensional lists dynamically:

matrix = [[1, 2], [3, 4]]
matrix.append([5, 6])

print(matrix)
# [[1, 2], [3, 4], [5, 6]]

Here is a conclusion for the article:

Conclusion

Lists are a fundamental and versatile data structure in Python. As outlined in this comprehensive guide, there are two main ways to create lists in Python - using square brackets [] and list comprehensions.

Square brackets allow you to initialize lists with predetermined elements or start with empty lists and append elements later. List comprehensions provide a more concise syntax for creating lists based on mathematical formulas or logic.

Once created, lists support easy access and modification of elements via indices. A host of built-in methods like append(), insert(), remove(), sort() etc. allow efficient in-place manipulation of list data.

Lists can be iterated over easily with for loops to access each element. Comprehensions and map/filter constructs provide even more succinct ways of processing list data without modifying the original.

Lists can be joined and split using the + operator and list() method respectively. Multidimensional lists or nested lists provide the ability to represent matrix-like data with heterogeneous sizes for inner lists.

In summary, lists are a versatile built-in data structure that form the backbone of many programs and algorithms in Python. Mastering the creation, manipulation and iteration of lists is essential for any Python programmer.