0

Can anybody explain me why this line gives me an error

['foo', 'foo_{}'.format(s) for s in range(0,5)] 

But it works properly when I do like these:

['foo_{}'.format(s) for s in range(0,5)] 

or even

['foo', ['foo_{}'.format(s) for s in range(0,5)]] 

and it gives me memory allocation when I do like this:

['foo', ('foo_{}'.format(s) for s in range(0,5))] 

I am learning and a newbie in Python and I am very curious why it produces me "Invalid Syntax" when I try this line of code

['foo', 'foo_{}'.format(s) for s in range(0,5)] 

Is there an alternative way to have an output of

Output: ['foo','foo_0','foo_1','foo_2','foo_3','foo_4'] 

without to do manually code?

Cheers!

3
  • ['foo'] + ['foo_{}'.format(s) for s in range(0,5)] is what I would use Commented Oct 11, 2018 at 6:51
  • stackoverflow.com/questions/44116557/… Commented Oct 11, 2018 at 6:53
  • @Skirrebattie Thank you for your alternative way! Commented Oct 11, 2018 at 7:01

3 Answers 3

1
['foo_{}'.format(s) for s in range(0,5)] 

The above implementation is List Comprehensions. You can check detail here, https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions

However by doing this: ['foo', 'foo_{}'.format(s) for s in range(0,5)] you are breaking List Comprehension implementation and actually you are defining a list whose first member is 'foo' and the other is'foo_{}'.format(s) for s in range(0,5)

Since the second member is neither a proper list element nor List Comprehensions syntax error is occured

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

1 Comment

Thank you for your answer and the source. This is very helpful. Think I should have a further study on that. Thanks again!
1

The expression a for b in c does not allow an implicit tuple in a (comma-separated expressions not enclosed in parentheses). That forces you to explicitly choose what exactly is combined by the comma:

[('foo', 'foo_{}'.format(s)) for s in range(0,5)] # [('foo', 'foo_0'), ('foo', 'foo_1'), ('foo', 'foo_2'), ('foo', 'foo_3'), ('foo', 'foo_4')] ['foo', ('foo_{}'.format(s) for s in range(0,5))] # ['foo', <generator object <genexpr> at 0x7fc2d41daca8>] 

1 Comment

Thank you! I really appreciate your answer :D
1

Use:

[('foo', 'foo_{}'.format(s)) for s in range(0,5)] 

I suspect this is because Python sees ['foo', 'foo_{}'.format(s) and thinks it's just a list. Then it sees for and is suddenly confused.

If you wrap 'foo', 'foo_{}'.format(s) in parentheses it removes the ambiguity.

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.