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']
2 Answers 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
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
Novato
I'll try both to see which approach helps in my case, thanks.
lang-py
import bisect
and use methodinsort
in combination withzfill