-1

I have a list filter = ['a', 'b', 'c']. I need to frame the following string out of the list "item -a item -b item -c". Which is the most efficient way to do this? Usually the list filter contains 100 to 200 items and each would be of length 100 - 150. Wouldn't that lead to overflow? And what is the maximum length of the string supported?

4
  • 7
    Don't use filter as variable name. "filter" is a Python function. Commented Sep 5, 2009 at 7:00
  • So many things are Python builtins that it's hard not to step on them now and then. It generally only affects the block of code it's in, so rather than trying to memorize every builtin function name, it's reasonably harmless to just avoid the ones you know and use, and rename variables later on if you miss one and need to use it. Commented Sep 5, 2009 at 8:17
  • 1
    There really aren't that many built-in functions. Just over 80. Commented Sep 5, 2009 at 8:50
  • 1
    special functions like filter usually are highlighted by the IDE. Commented Sep 5, 2009 at 11:52

3 Answers 3

4

A cleaner way to do this:

filter = ['a', 'b', 'c'] " ".join(["item -%s" % val for val in filter]) 

This works fine with large arrays, eg. filter = ['a'*1000] * 1000.

Sign up to request clarification or add additional context in comments.

Comments

1

You can use join (I believe join is the same in Python 3.0):

>>> l = ['a','b','c'] >>> print ' item -'.join([''] + l) >>> ' item -a item -b item -c' >>> print ' item -'.join([''] + l).lstrip(' ') # eat the leading space >>> 'item -a item -b item -c' 

2 Comments

You probably want to trim excess whitespace off the result too.
@Dominic Rodger, yes we can trim the leading space. join(l) won't give the result that Prabhu wants. The string would start 'a item...' instead of 'item -a...'
0

Again with join

But with f-string, this would be:

filter = ['a', 'b', 'c'] print(" ".join([f"item -{val}" for val in filter])) 

And as mentioned, avoid using keywords to name your vars.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.