Home python Adding an item to the beginning of the list Python

Adding an item to the beginning of the list Python




There is a append () function, but it adds an element to the end of the list, what function to use it to be added to the beginning?
For example

Add 5 to the beginning

Answer 1, Authority 100%

l = [10,100,55]

Option 1:

l.insert (0, 5)

Option 2:

l = [5] + l

Answer 2, Authority 75%

You can use the insert method, which inserts the item in the position specified by the first argument.


def main ():
  Li = [10, 100, 55]
  Li.insert (0, 5)
  Print (LI)
if __name__ == '__main__':
  Main ()


[5, 10, 100, 55]

Answer 3

l.insert (0,5)

l.insert – function with which we add to the very beginning of the list
(0), and then we indicate what we want to add
In our case – 5.

That is: L.Insert – add,
0 – the place to which you want to add an item,
and 5 – what you need to add.

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions