0

How to append a null value to the beginning of a list?

input:

t=[10,12,15,16]

Output:

t=['null',10,12,15,16]
Dave
  • 3,073
  • 7
  • 20
  • 33
kritz
  • 41
  • 1
  • 7

2 Answers2

8
t.insert(0, None) # to add a None value
t.insert(0, 'null') # to add the word 'null' as a string

You can add an element to 0th index as above.

Marlon Abeykoon
  • 11,927
  • 4
  • 54
  • 75
2
from collections import deque

t = [10, 12, 15, 16]
d_t = deque(t)
d_t.appendleft('null')

out:

deque(['null', 10, 12, 15, 16])

Deques are a generalization of stacks and queues (the name is pronounced “deck” and is short for “double- ended queue”). Deques support thread-safe, memory efficient appends and pops from either side of the deque with approximately the same O(1) performance in either direction. Though list objects support similar operations, they are optimized for fast fixed-length operations and incur O(n) memory movement costs for pop(0) and insert(0, v) operations which change both the size and position of the underlying data representation.

宏杰李
  • 11,820
  • 2
  • 28
  • 35