1

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']
asked Sep 8, 2022 at 14:45
3
  • what happens after 0099? does next value will be 0100? Commented Sep 8, 2022 at 14:47
  • @Novato : By default your value will be added at last in list ... if you are trying to add a new value Commented Sep 8, 2022 at 14:48
  • @Novato : Incase want to add in middle you can make use of import bisect and use method insort in combination with zfill Commented Sep 8, 2022 at 14:49

2 Answers 2

2

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']
answered Sep 8, 2022 at 14:48

Comments

1

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

answered Sep 8, 2022 at 14:57

1 Comment

I'll try both to see which approach helps in my case, thanks.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.