Picket At present This tutorial has a related video course created past the Real Python squad. Watch it together with the written tutorial to deepen your understanding: Building Lists With Python's .append()

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 lot out with this performance. I of those methods is .append() . With .append(), you tin add items to the end of an existing list object. You tin can also use .append() in a for loop to populate lists programmatically.

In this tutorial, y'all'll learn how to:

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

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

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

Python's .append() takes an object equally an statement and adds it to the end of an existing listing, correct after its last element:

>>>

                                            >>>                                numbers                =                [                i                ,                two                ,                three                ]                >>>                                numbers                .                append                (                iv                )                >>>                                numbers                [i, 2, 3, four]                          

Every time you call .append() on an existing list, the method adds a new item to the finish, or right side, of the list. The post-obit diagram illustrates the process:

Python's .append()

Python lists reserve extra space for new items at the end of the listing. A call to .append() will place new items in the available space.

In practice, yous can apply .append() to add together any kind of object to a given list:

>>>

                                            >>>                                mixed                =                [                1                ,                2                ]                >>>                                mixed                .                append                (                3                )                >>>                                mixed                [1, ii, 3]                >>>                                mixed                .                append                (                "iv"                )                >>>                                mixed                [1, two, iii, 'iv']                >>>                                mixed                .                suspend                (                5.0                )                >>>                                mixed                [i, 2, 3, 'four', 5.0]                          

Lists are sequences that tin hold different data types and Python objects, so you can use .append() to add any object to a given listing. In this case, you first add an integer number, then a string, and finally a floating-point number. However, y'all can also add another list, a dictionary, a tuple, a user-divers object, and so on.

Using .append() is equivalent to the following operation:

>>>

                                            >>>                                numbers                =                [                1                ,                two                ,                iii                ]                >>>                                # Equivalent to numbers.suspend(four)                                  >>>                                    numbers                  [                  len                  (                  numbers                  ):]                  =                  [                  four                  ]                                >>>                                numbers                [1, 2, 3, four]                          

In the highlighted line, you perform two operations at the same time:

  1. You accept a slice from numbers using the expression numbers[len(numbers):].
  2. You assign an iterable to that slice.

The slicing operation takes the infinite afterwards the terminal item in numbers. Meanwhile, the consignment operation unpacks the items in the list to the correct of the assignment operator and adds them to numbers. Withal, there's an important difference between using this kind of assignment and using .append(). With the assignment, yous can add several items to the end of your list at once:

>>>

                                            >>>                                numbers                =                [                1                ,                2                ,                three                ]                                  >>>                                    numbers                  [                  len                  (                  numbers                  ):]                  =                  [                  4                  ,                  5                  ,                  6                  ]                                >>>                                numbers                [i, 2, 3, 4, 5, 6]                          

In this case, the highlighted line takes a slice from the terminate of numbers, unpacks the items in the listing on the right side, and adds them to the slice as individual items.

.append() Adds a Unmarried Detail

With .suspend(), you tin add a number, list, tuple, dictionary, user-defined object, or whatever other object to an existing list. However, you lot need to keep in mind that .append() adds only a single particular or object at a time:

>>>

                                                  >>>                                    x                  =                  [                  ane                  ,                  2                  ,                  3                  ,                  four                  ]                  >>>                                    y                  =                  (                  5                  ,                  vi                  )                  >>>                                    x                  .                  append                  (                  y                  )                  >>>                                    10                  [1, 2, 3, 4, (v, 6)]                              

What happens here is that .append() adds the tuple object y to the end of your target list, x. What if you want to add each item in y to the end of 10 as an individual item and become [1, 2, 3, 4, 5, 6]? In that case, you tin can use .extend():

>>>

                                                  >>>                                    10                  =                  [                  1                  ,                  2                  ,                  3                  ,                  4                  ]                  >>>                                    y                  =                  (                  v                  ,                  half-dozen                  ,                  7                  )                  >>>                                    x                  .                  extend                  (                  y                  )                  >>>                                    x                  [1, 2, 3, 4, 5, six, 7]                  >>>                                    x                  =                  [                  1                  ,                  2                  ,                  3                  ,                  iv                  ]                  >>>                                    y                  =                  (                  5                  ,                  six                  ,                  7                  )                  >>>                                    # Equivalent to x.extend(y)                  >>>                                    x                  [                  len                  (                  x                  ):]                  =                  y                  >>>                                    x                  [i, 2, three, iv, v, 6, 7]                              

.extend() takes an iterable as an argument, unpacks its items, and adds them to the cease of your target list. This operation is equivalent to x[len(x):] = y, which is the same technique you saw in the previous section.

.suspend() Returns None

In practice, .append() does its work in place by modifying and growing the underlying listing. This ways that .append() doesn't return a new list with an additional new item at the cease. It returns None:

>>>

                                                  >>>                                    ten                  =                  [                  1                  ,                  2                  ,                  3                  ,                  iv                  ]                  >>>                                    y                  =                  x                  .                  suspend                  (                  5                  )                  >>>                                    y                  is                  None                  True                  >>>                                    ten                  [1, two, 3, iv, v]                              

Similar with several like methods, .append() changes the underlying listing in identify. Trying to use the return value of .append() is a common fault when information technology comes to learning how mutable sequence types work. Keeping this behavior of .append() in heed will help you lot prevent errors in your code.

Populating a List From Scratch

A mutual trouble that y'all might confront when working with lists in Python is how to populate them with several items for further processing. At that place are 2 ways to do this:

  1. Use .append() and a for loop
  2. Utilize a listing comprehension

In the next few sections, yous'll learn how and when to employ these techniques to create and populate Python lists from scratch.

Using .suspend()

One mutual employ case of .append() is to completely populate an empty list using a for loop. Inside the loop, you can manipulate the information and use .append() to add successive results to the listing. Say y'all need to create a function that takes a sequence of numbers and returns a list containing the square root of each number:

>>>

                                                  >>>                                    import                  math                  >>>                                    def                  square_root                  (                  numbers                  ):                  ...                                    result                  =                  []                  ...                                    for                  number                  in                  numbers                  :                  ...                                    result                  .                  append                  (                  math                  .                  sqrt                  (                  number                  ))                  ...                                    return                  result                  ...                  >>>                                    numbers                  =                  [                  1                  ,                  4                  ,                  9                  ,                  xvi                  ,                  25                  ,                  36                  ,                  49                  ,                  64                  ,                  81                  ]                  >>>                                    square_root                  (                  numbers                  )                  [i.0, 2.0, 3.0, 4.0, 5.0, 6.0, vii.0, 8.0, 9.0]                              

Here, yous ascertain square_root(), which takes a list of numbers as an argument. Within square_root(), you create an empty list called result and start a for loop that iterates over the items in numbers. In each iteration, you use math.sqrt() to calculate the foursquare root of the current number so apply .append() to add the event to result. Once the loop finishes, y'all return the resulting list.

This manner of populating lists is fairly common in Python. However, the language provides some user-friendly constructs that can make the procedure a lot more efficient and Pythonic. One of these constructs is a list comprehension, which you'll see in action in the next department.

Using a List Comprehension

In practise, you oft replace .suspend() with a listing comprehension when creating a listing from scratch and populating it. With a list comprehension, you can reimplement square_root() similar this:

>>>

                                                  >>>                                    import                  math                  >>>                                    def                  square_root                  (                  numbers                  ):                  ...                                    return                  [                  math                  .                  sqrt                  (                  number                  )                  for                  number                  in                  numbers                  ]                  ...                  >>>                                    numbers                  =                  [                  1                  ,                  4                  ,                  9                  ,                  16                  ,                  25                  ,                  36                  ,                  49                  ,                  64                  ,                  81                  ]                  >>>                                    square_root                  (                  numbers                  )                  [1.0, 2.0, 3.0, four.0, 5.0, 6.0, 7.0, 8.0, 9.0]                              

The list comprehension within square_root() creates a listing containing the square root of number for each number in numbers. This reads virtually like manifestly English. Besides, this new implementation will exist more efficient in terms of processing fourth dimension than the implementation that uses .suspend() along with a for loop.

To plow .suspend() into a list comprehension, you lot simply need to put its argument followed past the loop header (without the colon) inside a pair of square brackets.

Switching Back to .suspend()

Even though list comprehensions can exist more readable and efficient than .append() for populating lists, there might be situations where .append() is a amend selection.

Suppose you lot need square_root() to provide your users with detailed information about the progress of calculating the square root of the input list of numbers. To written report the operation progress, you tin can use print():

>>>

                                                  >>>                                    import                  math                  >>>                                    def                  square_root                  (                  numbers                  ):                  ...                                    result                  =                  []                  ...                                    n                  =                  len                  (                  numbers                  )                  ...                                    for                  i                  ,                  number                  in                  enumerate                  (                  numbers                  ):                  ...                                    impress                  (                  f                  "Processing number:                                    {                  number                  }                  "                  )                  ...                                    result                  .                  append                  (                  math                  .                  sqrt                  (                  number                  ))                  ...                                    print                  (                  f                  "Completed:                                    {                  int                  ((                  i                  +                  1                  )                  /                  n                  *                  100                  )                  }                  %"                  )                  ...                                    return                  result                  ...                  >>>                                    numbers                  =                  [                  1                  ,                  4                  ,                  9                  ,                  16                  ,                  25                  ,                  36                  ,                  49                  ,                  64                  ,                  81                  ]                  >>>                                    square_root                  (                  numbers                  )                  Processing number: i                  Completed: 11%                  ...                  Processing number: 81                  Completed: 100%                  [i.0, ii.0, 3.0, 4.0, 5.0, vi.0, 7.0, viii.0, 9.0]                              

Now think of how you can plough the body of square_root() into a list comprehension. Using print() within a list comprehension doesn't seem coherent or fifty-fifty possible unless you wrap part of the code in a helper function. Then, in this example, using .suspend() is the right pick.

The moral behind the above example is that there are some situations in which y'all tin can't replace .append() with a list comprehension or with any other construct.

Creating Stacks and Queues With Python's .append()

So far, you've learned how to utilise .suspend() to add together a unmarried item to a list or to populate lists from scratch. Now it'south time for a different and more specific kind of example. In this section, y'all'll learn how to utilise a Python list to create stack and queue data structures with the minimal required functionality using .suspend() and .pop().

Implementing a Stack

A stack is a data construction that stores items on superlative of each other. Items come in and out of the stack in a Last-In/Commencement-Out (LIFO) style. Typically, a stack implements two chief operations:

  1. push adds an item to the superlative, or terminate, of the stack.
  2. popular removes and returns the item at the top of the stack.

In a list, .append() is equivalent to a push operation, so y'all tin can use it to push items onto the stack. Lists also provide .pop(), which optionally takes an integer index as an argument. It returns the item at that index in the underlying listing and also removes the particular:

>>>

                                                  >>>                                    numbers                  =                  [                  1                  ,                  2                  ,                  3                  ]                  >>>                                    numbers                  .                  pop                  (                  1                  )                  ii                  >>>                                    numbers                  [1, 3]                  >>>                                    numbers                  .                  pop                  ()                  3                  >>>                                    numbers                  [1]                  >>>                                    numbers                  .                  pop                  ()                  one                  >>>                                    numbers                  []                  >>>                                    numbers                  .                  popular                  ()                  Traceback (most recent phone call last):                  File                  "<input>", line                  1, in                  <module>                  numbers                  .                  pop                  ()                  IndexError:                  pop from empty list                              

If you supply an integer index equally an argument to .pop(), then the method returns and removes the detail at that index in the list. Calling .pop() without an argument returns the last detail in the list. Notation that .popular() also removes the item from the underlying list. Finally, if you call .pop() on an empty list, and so you'll get an IndexError.

With this knowledge, you're gear up to implement a stack using .append() and .pop(). Here's a class that defines a stack. The class provides .push() and .pop() operations:

                                                  class                  Stack                  :                  def                  __init__                  (                  self                  ):                  cocky                  .                  _items                  =                  []                  def                  push                  (                  cocky                  ,                  detail                  ):                  self                  .                  _items                  .                  suspend                  (                  item                  )                  def                  pop                  (                  cocky                  ):                  try                  :                  return                  cocky                  .                  _items                  .                  pop                  ()                  except                  IndexError                  :                  print                  (                  "Empty stack"                  )                  def                  __len__                  (                  self                  ):                  return                  len                  (                  cocky                  .                  _items                  )                  def                  __repr__                  (                  cocky                  ):                  return                  f                  "Stack(                  {                  self                  .                  _items                  }                  )"                              

In Stack, you lot first initialize the example attribute ._items. This attribute holds an empty listing that y'all'll utilise to store the items in the stack. Then you code .push(), which implements the push operation using .suspend() on ._items.

You also implement the pop operation by calling .pop() on the underlying list, ._items. In this case, you utilize a try and except block to handle the IndexError that occurs when you call .pop() on an empty listing.

The special method .__len__() provides the required functionality for retrieving the length of the internal list ._items. The special method .__repr__() allows y'all to provide a convenient string representation of the stack when printing the data construction to the screen.

Hither are some examples of how you tin can use Stack in practice:

>>>

                                                  >>>                                    stack                  =                  Stack                  ()                  >>>                                    # Push items onto the acme of the stack                  >>>                                    stack                  .                  push                  (                  i                  )                  >>>                                    stack                  .                  push                  (                  two                  )                  >>>                                    # User-friendly printing format                  >>>                                    stack                  Stack([1, 2])                  >>>                                    impress                  (                  stack                  )                  Stack([1, 2])                  >>>                                    # Call up the length of the stack                  >>>                                    len                  (                  stack                  )                  2                  >>>                                    # Pop items from the superlative of the stack                  >>>                                    stack                  .                  pop                  ()                  two                  >>>                                    stack                  .                  pop                  ()                  ane                  >>>                                    stack                  .                  pop                  ()                  Empty stack                  >>>                                    stack                  Stack([])                              

That'south it! You've coded a stack data structure that implements the push and popular operations. Information technology as well provides functionality to get the length of the underlying list and to impress the entire stack in a convenient way.

Implementing a Queue

Queues are data structures that normally manage their items in a First-In/Beginning-Out (FIFO) fashion. Queues work like a pipe in which you button in new items at one end, and old items pop out from the other end.

Adding an particular to the end of a queue is known as an enqueue functioning, and removing an item from the forepart, or beginning, of a queue is known as a dequeue functioning.

You tin enqueue items using .append() and dequeue them using .pop(). This time, you need to provide 0 equally an argument to .pop() just to make it retrieve the first detail in the list instead of the final item. Here'southward a class that implements a queue data construction using a list to store its items:

                                                  class                  Queue                  :                  def                  __init__                  (                  self                  ):                  cocky                  .                  _items                  =                  []                  def                  enqueue                  (                  self                  ,                  item                  ):                  cocky                  .                  _items                  .                  append                  (                  item                  )                  def                  dequeue                  (                  cocky                  ):                  try                  :                  return                  cocky                  .                  _items                  .                  pop                  (                  0                  )                  except                  IndexError                  :                  print                  (                  "Empty queue"                  )                  def                  __len__                  (                  cocky                  ):                  return                  len                  (                  self                  .                  _items                  )                  def                  __repr__                  (                  self                  ):                  return                  f                  "Queue(                  {                  self                  .                  _items                  }                  )"                              

This form is quite like to your Stack. The main difference is that .pop() takes 0 as an argument to return and removes the first particular in the underlying listing, ._items, rather than the last.

The residuum of the implementation is almost identical but uses appropriate names, such as .enqueue() for calculation items and .dequeue() for removing them. You can use Queue the same way y'all used Stack in the to a higher place section: merely call .enqueue() to add items and .dequeue() to retrieve and remove them.

Using .append() in Other Data Structures

Other Python data structures likewise implement .suspend(). The operating principle is the aforementioned as the traditional .append() in a list. The method adds a unmarried item to the stop of the underlying data construction. Notwithstanding, in that location are some subtle differences.

In the next 2 sections, you lot'll learn how .append() works in other information structures, such as assortment.array() and collections.deque().

assortment.append()

Python'due south array.array() provides a sequence-like data structure that can compactly stand for an array of values. These values must be of the same data type, which is limited to C-way data types, such as characters, integer numbers, and floating-point numbers.

array.array() takes the following ii arguments:

Argument Content Required
typecode A single-character lawmaking that identifies the data type that the array tin can shop Yep
initializer A listing, bytes-like object, or iterable that serves every bit an initializer No

The documentation of array provides consummate data most all the allowed type codes that you tin can utilize when creating arrays. The following instance uses the "i" blazon code to create an array of integer numbers:

>>>

                                                  >>>                                    from                  array                  import                  array                  >>>                                    # Array of integer numbers                  >>>                                    int_array                  =                  assortment                  (                  "i"                  ,                  [                  1                  ,                  ii                  ,                  3                  ])                  >>>                                    int_array                  array('i', [ane, two, three])                  >>>                                    int_array                  [                  0                  ]                  1                  >>>                                    int_array                  [:                  2                  ]                  assortment('i', [1, 2])                  >>>                                    int_array                  [                  ii                  ]                  =                  4                  >>>                                    int_array                  array('i', [one, ii, iv])                              

To create an array, you need to provide a unmarried-character code to ascertain the data type of the values in the array. You tin can also provide an optional list of values with the advisable type to initialize the array.

Arrays back up most listing operations, such every bit slicing and indexing. Like lists, array.array() too provides a method called .append(). This method works similarly to its list counterpart, adding a unmarried value to the end of the underlying assortment. All the same, the value must have a information blazon that'southward uniform with the existing values in the assortment. Otherwise, you'll get a TypeError.

For example, if yous have an array with integer numbers, then y'all can't use .append() to add a floating-point number to that array:

>>>

                                                  >>>                                    from                  array                  import                  assortment                  >>>                                    a                  =                  array                  (                  "i"                  ,                  [                  i                  ,                  2                  ,                  3                  ])                  >>>                                    a                  array('i', [1, 2, 3])                  >>>                                    # Add together a floating-point number                  >>>                                    a                  .                  append                  (                  1.v                  )                  Traceback (nearly recent call concluding):                  File                  "<input>", line                  1, in                  <module>                  a                  .                  append                  (                  1.5                  )                  TypeError:                  integer argument expected, got bladder                              

If you endeavour to add together a floating-point number to a, then .append() fails with a TypeError. That'south because Python tin can't automatically convert a floating-point number into an integer number without losing information.

In contrast, if you accept an array with floating-point numbers and try to add together integer numbers to it, and so your operation will succeed:

>>>

                                                  >>>                                    from                  assortment                  import                  array                  >>>                                    float_array                  =                  array                  (                  "f"                  ,                  [                  1.0                  ,                  2.0                  ,                  3.0                  ])                  >>>                                    float_array                  array('f', [1.0, 2.0, 3.0])                  >>>                                    # Add and integer number                  >>>                                    float_array                  .                  append                  (                  4                  )                  >>>                                    float_array                  assortment('f', [one.0, 2.0, 3.0, 4.0])                              

Here, you employ .append() to add an integer number to an assortment of floating-point numbers. That's possible because Python can automatically convert integer numbers into floating-point numbers without losing data in the process.

deque.append() and deque.appendleft()

collections.deque() is some other data structure that implements a variation of .suspend(). A deque is a generalization of a stack and a queue especially designed to support fast and retentivity-efficient append and popular operations on both of its sides. Then if y'all need to create a data structure with these features, then consider using a deque instead of a list.

collections.deque() takes the following ii optional arguments:

Statement Content
iterable An iterable that serves equally an initializer
maxlen An integer number that specifies the maximum length of the deque

If you provide a value to maxlen, then your deque volition only store up to maxlen items. One time the deque is total, calculation a new item volition automatically cause the item at the opposite end of the deque to be discarded. On the other hand, if yous don't supply a value to maxlen, then the deque can abound to an arbitrary number of items.

In deques, .append() also adds a single particular to the end, or right side, of the underlying information structure:

>>>

                                                  >>>                                    from                  collections                  import                  deque                  >>>                                    d                  =                  deque                  ([                  1                  ,                  "a"                  ,                  three.0                  ])                  >>>                                    d                  deque([1, 'a', three.0])                  >>>                                    d                  .                  append                  (                  "b"                  )                  >>>                                    d                  deque([1, 'a', iii.0, 'b'])                              

Similar lists, deques can concur unlike types of items, and then .append() adds arbitrary items to the end of the deque. In other words, with .suspend(), you can add whatever object to a deque.

Besides .append(), deques besides provide .appendleft(), which adds a single item to the beginning, or left side, of a deque. Similarly, deques provide .pop() and .popleft() to remove items from the right and left side of the deque, respectively:

>>>

                                                  >>>                                    from                  collections                  import                  deque                  >>>                                    d                  =                  deque                  ([                  1                  ,                  "a"                  ,                  iii.0                  ])                  >>>                                    d                  .                  appendleft                  (                  -                  one.0                  )                  >>>                                    d                  deque([-1.0, 1, 'a', 3.0])                  >>>                                    d                  .                  popular                  ()                  3.0                  >>>                                    d                  .                  popleft                  ()                  -1.0                  >>>                                    d                  deque([1, 'a'])                              

The telephone call to .appendleft() adds -1.0 to the left side of d. On the other mitt, .popular() returns and removes the concluding item in d, and .popleft() returns and removes the first item. As an practise, you can try to implement your own stack or queue using a deque instead of a list. To do this, you can take advantage of the examples you saw in the department Creating Stacks and Queues With Python'due south .append().

Conclusion

Python provides a method called .append() that you tin use to add items to the end of a given listing. This method is widely used either to add a single item to the end of a list or to populate a list using a for loop. Learning how to use .append() will help you process lists in your programs.

In this tutorial, yous learned:

  • How .append() works
  • How to populate lists using .append() along with a for loop
  • When to supervene upon .append() with a listing comprehension
  • How .append() works in assortment.assortment() and collections.deque()

In addition, you coded some examples of how to use .append() to create data structures, such as stacks and queues. This noesis will permit you to use .append() to abound your lists efficiently and finer.

Watch Now This tutorial has a related video form created by the Existent Python team. Watch information technology together with the written tutorial to deepen your understanding: Edifice Lists With Python's .append()