madreher / LammpsInputBuilder

LammpsInputBuilder (or LIB) is a Python library designed to generate Lammps inputs from a molecular model, a forcefield, and a high-level definition of a simulation workflow.
MIT License
0 stars 0 forks source link

Update script generation to use list instead of str concat #7

Open madreher opened 1 month ago

madreher commented 1 month ago

Taken from https://docs.python-guide.org/writing/structure/

Bad

create a concatenated string from 0 to 19 (e.g. "012..1819")

nums = "" for n in range(20): nums += str(n) # slow and inefficient print(nums) Better

create a concatenated string from 0 to 19 (e.g. "012..1819")

nums = [] for n in range(20): nums.append(str(n)) print("".join(nums)) # much more efficient Best

create a concatenated string from 0 to 19 (e.g. "012..1819")

nums = [str(n) for n in range(20)] print("".join(nums)) One final thing to mention about strings is that using join() is not always best. In the instances where you are creating a new string from a pre-determined number of strings, using the addition operator is actually faster. But in cases like above or in cases where you are adding to an existing string, using join() should be your preferred method.

foo = 'foo' bar = 'bar'

foobar = foo + bar # This is good foo += 'ooo' # This is bad, instead you should do: foo = ''.join([foo, 'ooo'])