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 a more neat way to do so? Maybe a certain package or function?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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.
Method 2
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]
Method 3
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.
Method 4
letter = ["a", "b", "c", "d"]
letter.extend(["e", "f", "g", "h"])
letter.extend(("e", "f", "g", "h"))
print(letter)
...
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'e', 'f', 'g', 'h']
Method 5
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']
Method 6
I can’t add a comment, but I can’t be silent either
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 = len(lst) my_lst = lst + ['flag'+str(x) for x in range(n)] print(my_lst)
[‘A’, ‘B’, ‘flag0’, ‘flag1’]
Method 7
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)
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0