Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] Python List append() Method

#1
Python List append() Method

How can you add more elements to a given list? Use the append() method in Python. This tutorial shows you everything you need to know to help you master an essential method of the most fundamental container data type in the Python programming language.

Definition and Usage


The list.append(x) method—as the name suggests—appends element x to the end of the list.

Here’s a short example:

>>> l = []
>>> l.append(42)
>>> l
[42]
>>> l.append(21)
>>> l
[42, 21]

In the first line of the example, you create the list l. You then append the integer element 42 to the end of the list. The result is the list with one element [42]. Finally, you append the integer element 21 to the end of that list which results in the list with two elements [42, 21].

Syntax


You can call this method on each list object in Python. Here’s the syntax:

list.append(element)

Arguments



Argument Description
element The object you want to append to the list.

Code Puzzle


Now you know the basics. Let’s deepen your understanding with a short code puzzle—can you solve it?

# Puzzle
nums = [1, 2, 3]
nums.append(nums[:]) print(len(nums))
# What's the output of this code snippet?

You can check out the solution on the Finxter app. (I know it’s tricky!)

Examples


Let’s dive into a few more examples:

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

You can see that the append() method also allows for other objects. But be careful: you cannot append multiple elements in one method call. This will only add one new element (even if this new element is a list by itself). Instead, to add multiple elements to your list, you need to call the append() method multiple times.

Python List append() At The Beginning


What if you want to use the append() method at the beginning: you want to “append” an element just before the first element of the list.

Well, you should work on your terminology for starters. But if you insist, you can use the insert() method instead.

Here’s an example:

>>> lst = [1, 2, 3]
>>> lst.insert(0, 99)
>>> lst
[99, 1, 2, 3]

The insert(i, x) method inserts an element x at position i in the list. This way, you can insert an element to each position in the list—even at the first position. Note that if you insert an element at the first position, each subsequent element will be moved by one position. In other words, element i will move to position i+1.

Python List append() Multiple or All Elements


But what if you want to append not one but multiple elements? Or even all elements of a given iterable. Can you do it with append()? Well, let’s try:

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

The answer is no—you cannot append multiple elements to a list by using the append() method. But you can use another method: the extend() method:

>>> l = [1, 2, 3]
>>> l.extend([1, 2, 3])
>>> l
[1, 2, 3, 1, 2, 3]

You call the extend() method on a list object. It takes an iterable as an input argument. Then, it adds all elements of the iterable to the list, in the order of their occurrence.

Python List append() vs extend()


I shot a small video explaining the difference and which method is faster, too:



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

The method list.extend(iter) adds all elements in iter to the end of the list.

The difference between append() and extend() is that the former adds only one element and the latter adds a collection of elements to the list.

You can see this in the following example:

>>> l = []
>>> l.append(1)
>>> l.append(2)
>>> l
[1, 2]
>>> l.extend([3, 4, 5])
>>> l
[1, 2, 3, 4, 5]

In the code, you first add integer elements 1 and 2 to the list using two calls to the append() method. Then, you use the extend method to add the three elements 3, 4, and 5 in a single call of the extend() method.

Which method is faster — extend() vs append()?


To answer this question, I’ve written a short script that tests the runtime performance of creating large lists of increasing sizes using the extend() and the append() methods.

Our thesis is that the extend() method should be faster for larger list sizes because Python can append elements to a list in a batch rather than by calling the same method again and again.

I used my notebook with an Intel® Core™ i7-8565U 1.8GHz processor (with Turbo Boost up to 4.6 GHz) and 8 GB of RAM.

Then, I created 100 lists with both methods, extend() and append(), with sizes ranging from 10,000 elements to 1,000,000 elements. As elements, I simply incremented integer numbers by one starting from 0.

Here’s the code I used to measure and plot the results: which method is faster—append() or extend()?

import time def list_by_append(n): '''Creates a list & appends n elements''' lst = [] for i in range(n): lst.append(n) return lst def list_by_extend(n): '''Creates a list & extends it with n elements''' lst = [] lst.extend(range(n)) return lst # Compare runtime of both methods
list_sizes = [i * 10000 for i in range(100)]
append_runtimes = []
extend_runtimes = [] for size in list_sizes: # Get time stamps time_0 = time.time() list_by_append(size) time_1 = time.time() list_by_extend(size) time_2 = time.time() # Calculate runtimes append_runtimes.append((size, time_1 - time_0)) extend_runtimes.append((size, time_2 - time_1)) # Plot everything
import matplotlib.pyplot as plt
import numpy as np append_runtimes = np.array(append_runtimes)
extend_runtimes = np.array(extend_runtimes) print(append_runtimes)
print(extend_runtimes) plt.plot(append_runtimes[:,0], append_runtimes[:,1], label='append()')
plt.plot(extend_runtimes[:,0], extend_runtimes[:,1], label='extend()') plt.xlabel('list size')
plt.ylabel('runtime (seconds)') plt.legend()
plt.savefig('append_vs_extend.jpg')
plt.show()

The code consists of three high-level parts:

  • In the first part of the code, you define two functions list_by_append(n) and list_by_extend(n) that take as input argument an integer list size n and create lists of successively increasing integer elements using the append() and extend() methods, respectively.
  • In the second part of the code, you compare the runtime of both functions using 100 different values for the list size n.
  • In the third part of the code, you plot everything using the Python matplotlib library.

Here’s the resulting plot that compares the runtime of the two methods append() vs extend(). On the x axis, you can see the list size from 0 to 1,000,000 elements. On the y axis, you can see the runtime in seconds needed to execute the respective functions.


The resulting plot shows that both methods are extremely fast for a few tens of thousands of elements. In fact, they are so fast that the time() function of the time module cannot capture the elapsed time.

But as you increase the size of the lists to hundreds of thousands of elements, the extend() method starts to win:

For large lists with one million elements, the runtime of the extend() method is 60% faster than the runtime of the append() method.

The reason is the already mentioned batching of individual append operations.

However, the effect only plays out for very large lists. For small lists, you can choose either method. Well, for clarity of your code, it would still make sense to prefer extend() over append() if you need to add a bunch of elements rather than only a single element.

Python List append() vs insert()


Python List append() vs concatenate()


Python List append() If Not Exists


Python List append() Return New List


Python List append() Time Complexity, Memory, and Efficiency


Python List append() at Index


Python List append() Error


Python List append() Empty Element


Python List append() Thread Safe


Python List append() Sorted


Python List append() Dictionary


Python List append() For Loop One Line




https://www.sickgaming.net/blog/2020/03/...nd-method/
Reply



Possibly Related Threads…
Thread Author Replies Views Last Post
  [Tut] List Comprehension in Python xSicKxBot 0 2,106 08-23-2023, 07:54 PM
Last Post: xSicKxBot
  [Tut] Collections.Counter: How to Count List Elements (Python) xSicKxBot 0 1,956 08-19-2023, 06:03 AM
Last Post: xSicKxBot
  [Tut] 5 Effective Methods to Sort a List of String Numbers Numerically in Python xSicKxBot 0 1,556 08-16-2023, 08:49 AM
Last Post: xSicKxBot
  [Tut] Sort a List, String, Tuple in Python (sort, sorted) xSicKxBot 0 1,696 08-15-2023, 02:08 PM
Last Post: xSicKxBot
  [Tut] Python Converting List of Strings to * [Ultimate Guide] xSicKxBot 0 1,608 05-02-2023, 01:17 PM
Last Post: xSicKxBot
  [Tut] Python List of Tuples to DataFrame ? xSicKxBot 0 1,512 04-22-2023, 06:10 AM
Last Post: xSicKxBot
  [Tut] Python List of Dicts to Pandas DataFrame xSicKxBot 0 1,533 04-11-2023, 04:15 AM
Last Post: xSicKxBot
  [Tut] Python | Split String into List of Substrings xSicKxBot 0 1,441 12-11-2022, 12:17 PM
Last Post: xSicKxBot
  [Tut] Python Find in List [Ultimate Guide] xSicKxBot 0 1,429 12-09-2022, 11:35 PM
Last Post: xSicKxBot
  [Tut] Easiest Way to Convert List of Hex Strings to List of Integers xSicKxBot 0 1,459 11-25-2022, 11:54 AM
Last Post: xSicKxBot

Forum Jump:


Users browsing this thread:
1 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016