Python list extend return

Python List extend()

The extend() method in Python adds the iterable elements (list, tuple, string etc.) to the end of the list. The length of the list is increased by the number of elements present in the iterable.

In this tutorial, we will learn about the Python list extend() method with the help of examples.

Syntax of List extend()

The syntax of the extend() method is:

extend() Parameters

Return Value from List extend()

The extend() method modifies the list by adding the iterable elements to the end of the list, but it does not return any value.

Difference between append() and extend() method in Python

The append() method adds its argument as a single element to the end of the list and the length of the list will be increased by one. Whereas the extend() method iterates over the argument adding each items to the end of the list and the list is increased by the number of items added through iteration.

a =[1,2] b= [3,4] # append() method a.append(b) print("Using append() method", a) x =[1,2] y= [3,4] # extend() method x.extend(y) print("Using extend() method", x) 
Using append() method [1, 2, [3, 4]] Using extend() method [1, 2, 3, 4]

Example 1: How to use List extend() Method

# Programming list programming_list = ['C','C#','Python','Java'] frontend_programming =['CSS','HTML','JavaScript'] # add the frontend_progamming list into the existing list programming_list.extend(frontend_programming) # Note that iterable element is added to the end of the list print('The new extended list is :', programming_list) 
The new extended list is : ['C', 'C#', 'Python', 'Java', 'CSS', 'HTML', 'JavaScript'] 

Example 2: Add Elements of Tuple and Set to List

# Programming list programming_list = ['C','C#','Python','Java'] # frontend tuple frontend_programming =('CSS','HTML','JavaScript') # DB set db_set = # add the tuple to the existing list programming_list.extend(frontend_programming) # print the extended list after the adding tuple print('The new extended list after adding tuple is :', programming_list) # add the set to the existing list programming_list.extend(db_set) # print the extended list after the adding set print('The new extended list after adding set is :', programming_list) 
The new extended list after adding tuple is : ['C', 'C#', 'Python', 'Java', 'CSS', 'HTML', 'JavaScript'] The new extended list after adding set is : ['C', 'C#', 'Python', 'Java', 'CSS', 'HTML', 'JavaScript', 'SQL', 'NoSQL']

Example 3: Extend String to the List

Here the sting is also an iterable element. Hence we can extend the string to the list and each character in the string is appended into the list.

#list of characters my_list =['z','x','c'] # string with vowels vowels ='aeiou' # extend sting to list my_list.extend(vowels) print(my_list)

Источник

Читайте также:  Telegram bot sdk java

Python List extend() Method

Be on the Right Side of Change

How can you not one but multiple elements to a given list? Use the extend() 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.extend(iter) method adds all elements in the argument iterable iter to an existing list .

>>> lst = [1, 2, 3] >>> lst.extend([4, 5, 6]) >>> lst [1, 2, 3, 4, 5, 6]

In the first line of the example, you create the list lst . You then append the integers 4, 5, 6 to the end of the list using the extend() method. The result is the list with six elements [1, 2, 3, 4, 5, 6] .

Syntax

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

Arguments

Argument Description
iterable All the elements of the iterable will be added to the end of the list—in the order of their occurrence.

Video

Python List extend() At The Beginning

What if you want to use the extend() method at the beginning: you want to “add” a number of elements 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.

>>> 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 extend() vs +

List concatenation operator +: If you use the + operator on two integers, you’ll get the sum of those integers. But if you use the + operator on two lists, you’ll get a new list that is the concatenation of those lists.

l1 = [1, 2, 3] l2 = [4, 5, 6] l3 = l1 + l2 print(l3)

The problem with the + operator for list concatenation is that it creates a new list for each list concatenation operation. This can be very inefficient if you use the + operator multiple times in a loop.

How fast is the + operator really? Here’s a common scenario how people use it to add new elements to a list in a loop. This is very inefficient:

import time start = time.time() l = [] for i in range(100000): l = l + [i] stop = time.time() print("Elapsed time: " + str(stop - start))
Elapsed time: 14.438847541809082

The experiments were performed on my notebook with an Intel(R) Core(TM) i7-8565U 1.8GHz processor (with Turbo Boost up to 4.6 GHz) and 8 GB of RAM.

Читайте также:  Javascript with database connection

I measured the start and stop timestamps to calculate the total elapsed time for adding 100,000 elements to a list.

The result shows that it takes 14 seconds to perform this operation.

This seems slow (it is!). So let’s investigate some other methods to concatenate and their performance:

Python List extend() Performance

Here’s a similar example that shows how you can use the extend() method to concatenate two lists l1 and l2 .

l1 = [1, 2, 3] l2 = [4, 5, 6] l1.extend(l2) print(l1)

But is it also fast? Let’s check the performance!

Performance:

I performed a similar experiment as before for the list concatenation operator + .

import time start = time.time() l = [] l.extend(range(100000)) stop = time.time() print("Elapsed time: " + str(stop - start))

I measured the start and stop timestamps to calculate the total elapsed time for adding 100,000 elements to a list.

The result shows that it takes negligible time to run the code (0.0 seconds compared to 0.006 seconds for the append() operation above).

The extend() method is the most concise and fastest way to concatenate lists.

Python List append() vs extend()

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

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(R) Core(TM) 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.
Читайте также:  Capture all javascript events

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 Append List to Another List

To append list lst_1 to another list lst_2 , use the lst_2.extend(lst_1) method. Here’s an example:

>>> lst_1 = [1, 2, 3] >>> lst_2 = [4, 5, 6] >>> lst_2.extend(lst_1) >>> lst_2 [4, 5, 6, 1, 2, 3]

Python List extend() Returns None

The return value of the extend() method is None . The return value of the extend() method is not a list with the added elements. Assuming this is a common source of mistakes.

Here’s such an error where the coder wrongly assumed this:

>>> lst = [1, 2].extend([3, 4]) >>> lst[0] Traceback (most recent call last): File "", line 1, in lst[0] TypeError: 'NoneType' object is not subscriptable

It doesn’t make sense to assign the result of the extend() method to another variable—because it’s always None . Instead, the extend() method changes a list object without creating (and returning) a new list.

Here’s the correct version of the same code:

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

Now, you change the list object itself by calling the extend() method on it. You through away the None return value because it’s not needed.

Python List Concatenation

So you have two or more lists and you want to glue them together. This is called list concatenation. How can you do that?

Источник

Оцените статью