Append integer to beginning of list in Python

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 as integer, thus I cannot use append, or extend either. How would you do this?

2
Answers

Replies


To insert a variable at a given position in a list, you can use array.insert function. The syntax for it is array.insert(index, value). The index is the position where you want to insert the value. Here is an example of it.



x = 0


list = [1, 2, 3, 4, 5]


list.insert(0,x)


print(list)


[0, 1, 2, 3, 4, 5]


 

 


Since your variable ‘a’ is an integer, you can't add them both directly. One simple way to do it is through this code.



a = 5


list = [1,2,3,4]


print([a] + list)


 


You will get this output.



[5, 1, 2, 3, 4]


 

 
 

If you want to unleash your potential in this competitive field, please visit the Python course page for more information, where you can find the Python tutorials and Python frequently asked interview questions and answers as well.

 

This topic has been locked/unapproved. No replies allowed

Login to participate in this discussion.

Leave a reply

Before proceeding, please check your email for a verification link. If you did not receive the email, click here to request another.