-2

I have:

[10, 20, 30, 40, 1000, 5000, 0, 5000]

I need:

[-100,10, 20, 30, 40, 1000, 5000, 0, 5000]

How to add an item to the top of the array in Python 3.4?

int13h
  • 33
  • 3

3 Answers3

7

Try using list.insert(index, element)

listA = [10, 20, 30, 40, 1000, 5000, 0, 5000]
listA.insert(0, -100)
sumit-sampang-rai
  • 701
  • 1
  • 7
  • 16
5

Below code will do..

a = [10, 20, 30, 40, 1000, 5000, 0, 5000]
a.insert(0,-100)
print(a)
HadeS
  • 2,020
  • 19
  • 36
1

Easy, you should use the insert method.

alist=[1,2,3,4,5,6,7]

# to Add
alist.insert(0, 0)

print(alist)

The result will be

#/usr/bin/python3.4 test.py 
[0, 1, 2, 3, 4, 5, 6, 7]
user2360915
  • 1,100
  • 11
  • 30