In Python, I have a string which is a comma separated list of values. e.g. '5,2,7,8,3,4'
I need to add a new value onto the end and remove the first value,
e.g. '5,22,7,814,3,4' -> '22,7,814,3,4,1'
Currently, I do this as follows:
mystr = '5,22,7,814,3,4'
latestValue='1'
mylist = mystr.split(',')
mystr = ''
for i in range(len(mylist)-1):
if i==0:
mystr += mylist[i+1]
if i>0:
mystr += ','+mylist[i+1]
mystr += ','+latestValue
This runs millions of times in my code and I've identified it as a bottleneck, so I'm keen to optimize it to make it run faster.
What is the most efficient to do this (in terms of runtime)?
_, sep, rest = mystr.partition(",")
mystr = rest + sep + latestValue
It also works without any changes if mystr
is empty or a single item (without comma after it) due to str.partition
returns empty sep
if there is no sep
in mystr
.
You could use mystr.rstrip(",")
before calling partition()
if there might be a trailing comma in the mystr
.