Append several elements to list python

How to append multiple values to a list in Python

I am trying to figure out how to append multiple values to a list in Python. I know there are few methods to do so, such as manually input the values, or put the append operation in a for loop, or the append and extend functions. However, I wonder if there is neater way to do so? Maybe a certain package or function?

6 Answers 6

You can use the sequence method list.extend to extend the list by multiple values from any kind of iterable, being it another list or any other thing that provides a sequence of values.

>>> lst = [1, 2] >>> lst.append(3) >>> lst.append(4) >>> lst [1, 2, 3, 4] >>> lst.extend([5, 6, 7]) >>> lst.extend((8, 9, 10)) >>> lst [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>> lst.extend(range(11, 14)) >>> lst [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] 

So you can use list.append() to append a single value, and list.extend() to append multiple values.

Note that extend do not keep the structure of the element you add compared to append() . With your example using append, you would get [1, 2, 3, 4, [5, 6, 7], (8, 9, 10), range(11, 14)] . Python 3

@YohanObadia If that was the case for Python 3 in ’17, it is no longer the case — Python 3.7.7 does exactly what poke described.

Читайте также:  Java plug in is deprecated

@YohanObadia That makes no sense. Append appends ONE ELEMENT, thus it «keeps the structure». But that’s a duh, really. And @ Post169, nothing change between ’17 and today, extend and append still behave the same way, Yohan just didn’t understand what’s what.

Other than the append function, if by «multiple values» you mean another list, you can simply concatenate them like so.

>>> a = [1,2,3] >>> b = [4,5,6] >>> a + b [1, 2, 3, 4, 5, 6] 

I know this is old, and at the time of writing, 45 people have agreed your answer is good, but strictly speaking the OP asked to add items to a list, and this is creating a new list. Although a very similar/related statement would be: a += b. This would append and be unique from the primary answer above.

Given a = [1, 2, 3] , you can also append multiple elements as a += [4, 5, 6] . This sets a to [1, 2, 3, 4, 5, 6] . This does not create a new list; each element is appended to a . (Test this with a = [1, 2, 3]; b = a; a += [4, 5, 6] and you’ll see that a and b are still the same.)

If you take a look at the official docs, you’ll see right below append , extend . That’s what your looking for.

There’s also itertools.chain if you are more interested in efficient iteration than ending up with a fully populated data structure.

Another solution is to unpack both lists inside a new list and assign it back to the copy of the original list:

my_list[:] = [*my_list, *new_items] 
my_list = [1, 2] new_items = [3, 4, 5] my_list[:] = [*my_list, *new_items] my_list # [1, 2, 3, 4, 5] 

or assign to an empty slice as in Saumya Prasad’s answer (but at the end of the list):

length = len(my_list) my_list[length:length] = new_items my_list # [1, 2, 3, 4, 5] 

It’s worth noting that list.extend and slice assignment to an empty slice both modify the list in-place whereas itertools.chain or unpacking or + operator create a new list.

if the number of items was saved in a variable say n. you can use list comprehension and plus sign for list expansion.

lst = ['A', 'B'] n = 1 new_lst = lst + ['flag'+str(x) for x in range(n)] print(my_lst) >>> ['A','B','flag0','flag1'] 

One way you can work around this type of problem is —

Here we are inserting a list to the existing list by creating a variable new_values.

Note that we are inserting the values in the second index, i.e. a[2]

a = [1, 2, 7, 8] new_values = [3, 4, 5, 6] a.insert(2, new_values) print(a) 

But here insert() method will append the values as a list.

So here goes another way of doing the same thing, but this time, we’ll actually insert the values in between the items.

a = [1, 2, 7, 8] a[2:2] = [3,4,5,6] print(a) 

Источник

How to insert multiple elements into a list?

In JavaScript, I can use splice to insert an array of multiple elements in to an array: myArray.splice(insertIndex, removeNElements, . insertThese) . But I can’t seem to find a way to do something similar in Python without having concat lists. Is there such a way? (There is already a Q&A about inserting single items, rather than multiple.) For example myList = [1, 2, 3] and I want to insert otherList = [4, 5, 6] by calling myList.someMethod(1, otherList) to get [1, 4, 5, 6, 2, 3]

@mgilson No, extend only adds to the end, right? I’d like to be able to insert it anywhere in the list as indicated by insertIndex

@AlanH the example in the question is exactly what that other question describes how to do: mylist[0:1] + otherlist + mylist[2:]

Disagree with duplicate. The other question wants to insert one given item into multiple unrelated locations stackoverflow.com/questions/2218238/…

7 Answers 7

To extend a list, you just use list.extend . To insert elements from any iterable at an index, you can use slice assignment.

>>> a = list(range(10)) >>> a [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> a[5:5] = range(10, 13) >>> a [0, 1, 2, 3, 4, 10, 11, 12, 5, 6, 7, 8, 9] 

This does the job, but doesn’t answer the actual question directly. The answer should have been something like myList[1:1] = otherList .

@Manngo This does exactly what’s asked and should be the accepted answer. (Though I don’t know if, performance-wise, it’s all same)

Python lists do not have such a method. Here is helper function that takes two lists and places the second list into the first list at the specified position:

def insert_position(position, list1, list2): return list1[:position] + list2 + list1[position:] 

I’m not certain this question is still being followed but I recently wrote a short code that resembles what is being asked here. I was writing an interactive script to perform some analyses so I had a series of inputs serving to read in certain columns from a CSV:

X = input('X COLUMN NAME?:\n') Y = input('Y COLUMN NAME?:\n') Z = input('Z COLUMN NAME?:\n') cols = [X,Y,Z] 

Then, I brought the for-loop into 1 line to read into the desired index position:

[cols.insert(len(cols),x) for x in input('ENTER COLUMN NAMES (COMMA SEPARATED):\n').split(', ')] 

This may not necessarily be as concise as it could be (I would love to know what might work even better!) but this might clean some of the code up.

The following accomplishes this while avoiding creation of a new list. However I still prefer @RFV5s method.

def insert_to_list(original_list, new_list, index): tmp_list = [] # Remove everything following the insertion point while len(original_list) > index: tmp_list.append(original_list.pop()) # Insert the new values original_list.extend(new_list) # Reattach the removed values original_list.extend(tmp_list[::-1]) return original_list 

Note that it’s necessary to reverse the order of tmp_list because pop() gives up the values from original_list backwards from the end.

Источник

How to add multiple values to a list in one line in Python?

I have a list that I want to add multiple values to, and I use append() , as below, to add 10 more digits:

>>> x = [1, 2, 3, 4] >>> x.append(5, 6, 7, 8, 9, 10, 11, 12, 13, 14) Traceback (most recent call last): File "", line 1, in TypeError: append() takes exactly one argument (10 given) 
>>> x = [1, 2, 3, 4] >>> x.append([5, 6, 7, 8, 9, 10, 11, 12, 13, 14]) >>> x [1, 2, 3, 4, [5, 6, 7, 8, 9, 10, 11, 12, 13, 14]] 
>>> x = [1, 2, 3, 4] >>> x.what_I_want([5, 6, 7, 8, 9, 10, 11, 12, 13, 14]) >>> x [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] 

Is the first change that I made to take away the TypeError the correct change to make? Or is that why this isn’t working?

4 Answers 4

>>> x = [1, 2, 3, 4] >>> x.extend([5, 6, 7, 8, 9, 10, 11, 12, 13, 14]) >>> x [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] 

For completeness, your other options are creating a new list as a concatenation of the two lists:

>>> x = [1, 2, 3, 4] >>> x + [5, 6, 7, 8, 9, 10, 11, 12, 13, 14] [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] >>> x += [5, 6, 7, 8, 9, 10, 11, 12, 13, 14] >>> x [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] 

And assigning into the empty slice at the end:

>>> x = [1, 2, 3, 4] >>> x[len(x):len(x)] = [5, 6, 7, 8, 9, 10, 11, 12, 13, 14] >>> x [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] 
>>> x = [1, 2, 3, 4] >>> x.extend([5, 6, 7, 8, 9, 10, 11, 12, 13, 14]) >>> x [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] 

Instead of typing out the numbers from 5 through 15, use a range() :

>>> x = [1, 2, 3, 4] >>> x.extend(range(5, 15)) >>> x [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] 

The first edit that you made was correct, since you can only append one item at a time, not a tuple like (5, 6, 7, 8, 9, 10, 11, 12, 13, 14)

If he had tried to append a tuple ( x.append((5, 6, 7)) ), he would have been successful, just as with the list. The problem is trying to pass more than one argument to the method.

The list append() method takes a single argument, which is added to the list. Thus, when you pass it a list, that list becomes the new last element of the list to which it is appended. By maintaining such consistency Python allows us to conveniently create and process lists of lists and more complicated data structures. But it does mean append() is not the answer you are looking for.

The simplest answer to your problem I can think of is

This will work fine in Python 2, but in Python 3 range() is a generator, so you have to use

Lists can be added together as can tuples, and it works just like string concatenation.

Источник

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