0

I'm using the following single line of python code to print out a specific pattern which I showed at the bottom.

My code:

print(*[a, b, for a in range(5): for b in range(3)], sep='\n')

After executing the above code, I'm getting an invalid syntax error but I could not find any syntax error there.

Error:

Getting error : SyntaxError: invalid syntax  

My desired output as follow:

1 1  
1 2  
1 3  
1 4  
2 1  
2 2  
2 3  
2 4

How can I print this pattern in a single line of code?

I appreciate your assistance.

1
  • As of now, answers provide only solutions, not explanations. So: Why syntax error? List comprehension doesn't allow 1) tuples to be without parentheses (because of commas that human may interpret wrongly), 2) commas and colons in strange places (before/after for, here: comma between b and for, colon between two fors). This would make it: print(*[(a, b) for a in range(5) for b in range(3)], sep='\n') Of course that only solves the error, not the formatting - but the string formatting was already explained by others. :) Commented Mar 9, 2020 at 9:40

3 Answers 3

2

Go for:

print(*[f'{a} {b}' for a in range(5) for b in range(3)], sep='\n')

0 0

0 1

0 2

1 0

1 1

1 2

...

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

3 Comments

f'{a} {b}' would you please elaborate these part?
@KittoMi this is a python f-string, this is like a string but everything put between {} is evaluated e.g. print(f'1+2={1 + 2}') prints '1+2=3'
*f-strings were introduced in Python 3.6, not 3.7
2

Another thing that other answers don't have into account is that, in order to have the pattern that you are looking for, range should start at 1 and a and b should change places.

print(*["{} {}".format(a,b) for a in range(1, 3) for b in range(1, 5)], sep='\n')

2 Comments

List comprehensions are for creating a list. Not for iterating a call to print.
You are right. I edited the answer. It works anyway, but it is cleaner this way.
1

You have made two syntax errors in your list comprehension

In a list comprehension the for loop is not an expression so you don't write the colon:.

You want to store a string in the list comprehension. The expression that is stored by the list comprehension is not part of the print function. There are multiple ways of constructing the string. In this case f-strings are a good solution.

The correct syntax is

print(*[f"{a} {b}") for a in range(5) for b in range(3)], sep='\n')

If a list comprehension becomes too long, i tend to split it over multiple lines.

data = [
    f"{a} {b}"
    for a in range(5)
    for b in range(3)
]
print(*data, sep="\n")

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.