Python List.append() – How to Append to a List in Python

Lists are one of the most versatile and essential data structures in Python. They allow you to store ordered collections of items, which can be of any data type – numbers, strings, booleans, and even other lists! Lists are mutable, meaning you can change their contents by modifying, adding, or removing elements.

One of the most common operations when working with lists is appending new elements to the end. Fortunately, Python provides a built-in list method to make this easy: append(). In this guide, we‘ll take an in-depth look at how to use the list.append() method effectively in your Python code.

Creating and Accessing Python Lists

Before we dive into appending elements, let‘s briefly review the basics of creating and working with lists in Python. To create a list, use square brackets [] and separate elements with commas:

numbers = [1, 2, 3, 4, 5]
fruits = [‘apple‘, ‘banana‘, ‘orange‘] 
mixed = [10, ‘hello‘, True, [1, 2]]

As you can see, lists can contain any mix of data types, including other lists nested inside. You can also create an empty list that you plan to populate later:

empty_list = []

To access elements in a list, use indexing with square brackets. Lists are zero-indexed, meaning the first element is at index 0, the second at index 1, and so on. You can also use negative indices to access elements from the end of the list, where -1 is the last element.

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

print(numbers[0])  # 1
print(numbers[3])  # 4  
print(numbers[-1]) # 5

You can modify list elements by assigning a new value to a specific index:

fruits = [‘apple‘, ‘banana‘, ‘orange‘]

fruits[1] = ‘blueberry‘
print(fruits)  # [‘apple‘, ‘blueberry‘, ‘orange‘]

Appending Elements with list.append()

Now that we‘ve covered list basics, let‘s get to the star of the show: the append() method. append() allows you to add an element to the end of a list. It takes a single argument, which is the element you want to add.

numbers = [1, 2, 3]

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

You can append elements of any data type, including variables:

fruits = [‘apple‘, ‘banana‘]
new_fruit = ‘orange‘

fruits.append(new_fruit) 
print(fruits)  # [‘apple‘, ‘banana‘, ‘orange‘]

append() modifies the original list directly, so you don‘t need to assign the result back to the variable. This is different from concatenation, which creates a new list:

numbers = [1, 2, 3]

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

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

Appending Lists to Lists

You can also use append() to add a list as a single element inside another list, creating a nested list structure:

main_list = [1, 2, 3]
sub_list = [4, 5]

main_list.append(sub_list)
print(main_list)  # [1, 2, 3, [4, 5]]

Notice that the sub_list is added as a single element at the end of main_list. If you instead want to add each element of sub_list individually to the end of main_list, use the extend() method:

main_list = [1, 2, 3]
sub_list = [4, 5]

main_list.extend(sub_list)
print(main_list)  # [1, 2, 3, 4, 5]

Appending in Loops and Conditionals

append() really shines when used in loops or conditional statements to dynamically build lists. For example, you can use a for loop to append the squares of numbers to a list:

squares = []

for i in range(1, 6):
    squares.append(i ** 2)

print(squares)  # [1, 4, 9, 16, 25]  

Or use conditionals to filter out values before appending:

evens = []
odds = []

for i in range(1, 11):
    if i % 2 == 0:
        evens.append(i)
    else:
        odds.append(i)

print(evens)  # [2, 4, 6, 8, 10]        
print(odds)   # [1, 3, 5, 7, 9]

Efficiency of append()

One of the reasons append() is so widely used is its efficiency. Appending to the end of a list is an O(1) operation – it takes constant time, regardless of the size of the list. This is because Python doesn‘t need to shift existing elements to make room for the new one; it simply adds it to the end.

In contrast, inserting an element at the beginning or middle of a list with insert() is an O(n) operation. This is because Python needs to shift all elements after the insertion point over by one index to make space. For large lists, this can get quite slow.

So when building a list dynamically, it‘s usually best to append elements and then reverse the order if needed, rather than inserting at the beginning each time.

Removing Elements with pop()

As a quick aside – while we‘re discussing adding elements, it‘s worth mentioning the inverse operation: removing elements. The pop() method removes and returns the element at a given index (default is -1, the last element).

numbers = [1, 2, 3, 4]

last = numbers.pop() 
print(last)      # 4
print(numbers)   # [1, 2, 3]

second = numbers.pop(1)
print(second)    # 2  
print(numbers)   # [1, 3]

Like append(), pop() is an O(1) operation when removing from the end of the list. However, popping from the beginning or middle is O(n), as the remaining elements need to be shifted over to fill the gap.

Conclusion

In this guide, we‘ve explored the power and simplicity of using Python‘s built-in list.append() method to add elements to the end of a list. We‘ve seen how to:

  • Create and access list elements using indexing
  • Append elements of various data types to a list
  • Add lists as elements to create nested list structures
  • Use append() inside loops and conditionals to dynamically build lists
  • Leverage the O(1) efficiency of appending to the end of a list

Mastering append() is a key skill for any Python developer, as it allows you to flexibly and efficiently work with this essential data structure. So go forth and append elements to your heart‘s content!

Additional Resources

To dive even deeper into working with Python lists and the append() method, check out these resources:

Happy coding!

Similar Posts