5

I would appreciate suggestions for a more efficient way to conditionally concatenate a list.

This technique seems to work:

sentence = ['this ','is ','are ','a ','sentence']
string = ''
for i in sentence:
    if i != 'are ':
        string += i

2 Answers2

15

You can use str.join and a list comprehension:

sentence = ['this ','is ','are ','a ','sentence']
string = ''.join([i for i in sentence if i != 'are '])

And yes, I used a list comprehension purposefully. It is generally faster than a generator expression when using str.join.

Community
  • 1
  • 1
6

You can filter out the are and concatenate with "".join, like this

>>> "".join(item for item in sentence if item != "are ")

Here, "".join means that, join the strings returned by the generator expression with no filling character. If you have ",".join, then all the elements will be joined by ,.

Actually, "".join will be faster with a list, than with a generator expression. So, just convert the generator expression to a list with list comprehension, like this

>>> "".join([item for item in sentence if item != "are "])
thefourtheye
  • 233,700
  • 52
  • 457
  • 497