Home > Enterprise >  Add an element to a list base on the value of the list (python)
Add an element to a list base on the value of the list (python)

Time:09-09

So I have a list of x elements as such:

list = ['0001', '0002', '0003', '0004', '0005', '0006', '0007', '0008', '0009']

If a element is removed (ex: '0004'):

['0001', '0002', '0003', '0005', '0006', '0007', '0008', '0009']

How can I add an element base on the last value which in this case is '0009'?

['0001', '0002', '0003', '0005', '0006', '0007', '0008', '0009', '0010']

CodePudding user response:

You can just create a zero padded value adding 1 to to the numeric value at last using str.zfill, then append to the list:

lst = ['0001', '0002', '0003', '0004', '0005', '0006', '0007', '0008', '0009']
print(lst.pop(3))
val = str(int(lst[-1]) 1).zfill(4)
lst.append(val)
print(lst)

OUTPUT:

0004
['0001', '0002', '0003', '0005', '0006', '0007', '0008', '0009', '0010']

CodePudding user response:

Slight modification to author code : @ThePyGuy

Just to dynamically define the padding of zero based on '0004'

Code :

lst = ['0001', '0002', '0003', '0004', '0005', '0006', '0007', '0008', '0009']
lng=len(str(lst[3]))
val = str(int(lst[-1]) 1).zfill(lng)
lst.append(val)
print(lst)

Incase any issue feel free to guide me

  • Related