0

I want to print a list object with 5 items in a for loop, would like to print only the 3rd item(i.e. _ == 2) with new line while discarding newlines for other items.

I understand that I can achieve the desired result by converting the integer '2' as string and then concatenating it with a new line character, but is there a way to specify "new" parameters based on conditions in the print function?

Here is the desired result

012
34
for _ in range(5):
    print(str(_) + "\n" if _== 2 else _ , end='')

Obviously syntax error is preventing the use of new parameter in condition.

syntax_err.py

for _ in range(5):
    print((_ , end='') if _!= 2 else _)

nor can I do this:

for _ in range(5):
    print(_ if _== 2 else (_, end=''))
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
  • 3
    A generator expression needs to be parenthesised if it's not the only argument. Note the underscore typically represents a value that isn't going to be used, it's very confusing to see it here. – jonrsharpe Jan 16 '21 at 22:49
  • 1
    @jonrsharpe For reference: [What is the purpose of the single underscore “_” variable in Python?](https://stackoverflow.com/q/5893163/4518341) – wjandrea Jan 16 '21 at 22:51
  • @wjandrea yes, exactly. – jonrsharpe Jan 16 '21 at 22:52
  • BTW, welcome to SO! Check out the [tour], and [ask] if you want tips. This is a decent first question, keep it up! :) – wjandrea Jan 16 '21 at 22:59

2 Answers2

1
for x in range(5):
    end = "\n" if x == 2 else ""
    print(x, end=end)
DanDayne
  • 154
  • 6
1

You can give a conditional expression to the keyword argument, end.

for i in range(5):
    print(i, end="\n" if i==2 else '')

Output:

012
34

By the way, a single underscore usually represents a throwaway variable, which makes your code confusing, so I'm using i instead.

wjandrea
  • 28,235
  • 9
  • 60
  • 81