benji
benji

Reputation: 196

Invalid syntax of FOR loop

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!

Upvotes: 0

Views: 125

Answers (3)

Wodin
Wodin

Reputation: 3538

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.

Upvotes: 1

kaan bobac
kaan bobac

Reputation: 747

['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

Upvotes: 1

user2390182
user2390182

Reputation: 73498

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>]

Upvotes: 1

Related Questions