Novato
Novato

Reputation: 19

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

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']

Upvotes: 1

Views: 32

Answers (2)

codeholic24
codeholic24

Reputation: 995

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

Upvotes: 1

ThePyGuy
ThePyGuy

Reputation: 18466

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']

Upvotes: 2

Related Questions