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)?
Concatenate Strings using the Join As shown above, using the + operator is more efficient. It takes less time for execution.
Concatenate multiple strings The most common among them is using the plus (“+”) operator. You can combine both string variables and string literals using the “+” operator. However, there's another method that allows an easy way of concatenating multiple strings. It is using the in-place (+=) operator.
There are two ways to concatenate strings in Java: By + (String concatenation) operator. By concat() method.
Summary: Using the string concatenation operator is slightly faster than using format string literals. Unless you are performing many hundreds of thousands of string concatenations and need them done very quickly, the implementation chosen is unlikely to make a difference.
Use this:
if mystr == '':
mystr = latestValue
else:
mystr = mystr[mystr.find(",")+1:] + "," + latestValue
This should be much faster than any solution which splits the list. It only finds the first occurrence of ,
and "removes" the beginning of the string. Also, if the list is empty, then mystr
will be just latestValue
(insignificant overhead added by this) -- thanks Paulo Scardine for pointing that out.
_, 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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With