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!

benji
  • 186
  • 1
  • 11

3 Answers3

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.

Wodin
  • 3,243
  • 1
  • 26
  • 55
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>]
user2390182
  • 72,016
  • 6
  • 67
  • 89
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

kaan bobac
  • 729
  • 4
  • 8
  • 1
    Thank you for your answer and the source. This is very helpful. Think I should have a further study on that. Thanks again! – benji Oct 11 '18 at 06:59