2

why can't I do something like this:

files = [file for file in ['default.txt'].append(sys.argv[1:]) if os.path.exists(file)]
2
  • 1
    I presume you've imported os? But note: this is a list comprehension... not a generator expression. Commented Mar 22, 2011 at 11:30
  • 1
    What makes you think append() returns a value? Where did you read there? Where did you see any example like that? Commented Mar 22, 2011 at 14:37

2 Answers 2

10

list.append doesn't return anything in Python:

>>> l = [1, 2, 3]
>>> k = l.append(5)
>>> k
>>> k is None
True

You may want this instead:

>>> k = [1, 2, 3] + [5]
>>> k
[1, 2, 3, 5]
>>> 

Or, in your code:

files = [file for file in ['default.txt'] + sys.argv[1:] if os.path.exists(file)]
Sign up to request clarification or add additional context in comments.

2 Comments

It is a fact to which I totally forgot
@Martin: no worries, we all forget things. Which is why it's always best to write short code samples in the interactive prompt before writing long comprehensions
4

You could also use itertools.chain if you don't want to duplicate lists.

files = [file for file in itertools.chain(['default.txt'], sys.argv[1:])
                  if os.path.exists(file)]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.