Python's .append(): Add Items To Your Lists In Place

Table of Contents

  • Adding Items to a List With Python’s .append()
    • .append() Adds a Single Item
    • .append() Returns None
  • Populating a List From Scratch
    • Using .append()
    • Using a List Comprehension
    • Switching Back to .append()
  • Creating Stacks and Queues With Python’s .append()
    • Implementing a Stack
    • Implementing a Queue
  • Using .append() in Other Data Structures
    • array.append()
    • deque.append() and deque.appendleft()
  • Conclusion
Remove ads

Recommended Course

Building Lists With Python's .append() (40m)

Adding items to a list is a fairly common task in Python, so the language provides a bunch of methods and operators that can help you out with this operation. One of those methods is .append(). With .append(), you can add items to the end of an existing list object. You can also use .append() in a for loop to populate lists programmatically.

In this tutorial, you’ll learn how to:

  • Work with .append()
  • Populate lists using .append() and a for loop
  • Replace .append() with list comprehensions
  • Work with .append() in array.array() and collections.deque()

You’ll also code some examples of how to use .append() in practice. With this knowledge, you’ll be able to effectively use .append() in your programs.

Free Download: Get a sample chapter from Python Basics: A Practical Introduction to Python 3 to see how you can go from beginner to intermediate in Python with a complete curriculum, up-to-date for Python 3.8.

Adding Items to a List With Python’s .append()

Python’s .append() takes an object as an argument and adds it to the end of an existing list, right after its last element:

Python >>> numbers = [1, 2, 3] >>> numbers.append(4) >>> numbers [1, 2, 3, 4]

Tag » Add Element If Not In List Python