Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append integer to beginning of list in Python [duplicate]

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?

like image 271
gen Avatar asked Jul 28 '13 17:07

gen


People also ask

How do you append a value to the beginning of a list in Python?

Use the + Operator to Append an Element to the Front of a List in Python. Another approach to append an element to the front of a list is to use the + operator. Using the + operator on two or more lists combines them in the specified order.

How do you append to a position in a list?

The Python list data type has three methods for adding elements: append() - appends a single element to the list. extend() - appends elements of an iterable to the list. insert() - inserts a single item at a given position of the list.

Does Python list append make a copy?

💡 Tips: When you use . append() the original list is modified. The method does not create a copy of the list – it mutates the original list in memory.


1 Answers

>>>var=7 >>>array = [1,2,3,4,5,6] >>>array.insert(0,var) >>>array [7, 1, 2, 3, 4, 5, 6] 

How it works:

array.insert(index, value)

Insert an item at a given position. The first argument is the index of the element before which to insert, so array.insert(0, x) inserts at the front of the list, and array.insert(len(array), x) is equivalent to array.append(x).Negative values are treated as being relative to the end of the array.

like image 115
Nullify Avatar answered Oct 17 '22 07:10

Nullify