[python] Append integer to beginning of list in Python

I have an integer and a list. I would like to make a new list of them beginning with the variable and ending with the list. Writing a + list I get errors. The compiler handles a as integer, thus I cannot use append, or extend either. How would you do this?

This question is related to python list variables append

The answer is


list_1.insert(0,ur_data)

make sure that ur_data is of string type so if u have data= int(5) convert it to ur_data = str(data)


None of these worked for me. I converted the first element to be part of a series (a single element series), and converted the second element also to be a series, and used append function.

l = ((pd.Series(<first element>)).append(pd.Series(<list of other elements>))).tolist()

>>> a = 5
>>> li = [1, 2, 3]
>>> [a] + li  # Don't use 'list' as variable name.
[5, 1, 2, 3]

New lists can be made by simply adding lists together.

list1 = ['value1','value2','value3']
list2 = ['value0']
newlist=list2+list1
print(newlist)

Based on some (minimal) benchmarks using the timeit module it seems that the following has similar if not better performance than the accepted answer

new_lst = [a, *lst]

As with [a] + list this will create a new list and not mutate lst.

If your intention is to mutate the list then use lst.insert(0, a).


You can use Unpack list:

a = 5

li = [1,2,3]

li = [a, *li]

=> [5, 1, 2, 3]


Another way of doing the same,

list[0:0] = [a]

Alternative:

>>> from collections import deque

>>> my_list = deque()
>>> my_list.append(1)       # append right
>>> my_list.append(2)       # append right
>>> my_list.append(3)       # append right
>>> my_list.appendleft(100) # append left
>>> my_list

deque([100, 1, 2, 3])

>>> my_list[0]

100

[NOTE]:

collections.deque is faster than Python pure list in a loop Relevant-Post.


Note that if you are trying to do that operation often, especially in loops, a list is the wrong data structure.

Lists are not optimized for modifications at the front, and somelist.insert(0, something) is an O(n) operation.

somelist.pop(0) and del somelist[0] are also O(n) operations.

The correct data structure to use is a deque from the collections module. deques expose an interface that is similar to those of lists, but are optimized for modifications from both endpoints. They have an appendleft method for insertions at the front.

Demo:

In [1]: lst = [0]*1000
In [2]: timeit -n1000 lst.insert(0, 1)
1000 loops, best of 3: 794 ns per loop
In [3]: from collections import deque
In [4]: deq = deque([0]*1000)
In [5]: timeit -n1000 deq.appendleft(1)
1000 loops, best of 3: 73 ns per loop

Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to list

Convert List to Pandas Dataframe Column Python find elements in one list that are not in the other Sorting a list with stream.sorted() in Java Python Loop: List Index Out of Range How to combine two lists in R How do I multiply each element in a list by a number? Save a list to a .txt file The most efficient way to remove first N elements in a list? TypeError: list indices must be integers or slices, not str Parse JSON String into List<string>

Examples related to variables

When to create variables (memory management) How to print a Groovy variable in Jenkins? What does ${} (dollar sign and curly braces) mean in a string in Javascript? How to access global variables How to initialize a variable of date type in java? How to define a variable in a Dockerfile? Why does foo = filter(...) return a <filter object>, not a list? How can I pass variable to ansible playbook in the command line? How do I use this JavaScript variable in HTML? Static vs class functions/variables in Swift classes?

Examples related to append

List append() in for loop ValueError: all the input arrays must have same number of dimensions Append a tuple to a list - what's the difference between two ways? How merge two objects array in angularjs? How to add an element at the end of an array? Appending a list or series to a pandas DataFrame as a row? Can someone explain how to append an element to an array in C programming? How to append elements at the end of ArrayList in Java? Append value to empty vector in R? How to append new data onto a new line