-2

I have the following code:

a = True

x = [2, 7, 8]

print(x)

if a:
    x.append(10)
    
print(x)

# one line ???
y = [2, 7, 8 if a: 10]

print(y)

I'm trying to use if statement in one line, but I get invalid syntax. Any ideas?

Joel
  • 1,805
  • 1
  • 22
  • 22
  • 1
    I think you need to do: `y = [2, 7, 8, 10] if a else [2, 7, 8] `, see: https://book.pythontips.com/en/latest/ternary_operators.html, or a better link might be this answer: https://stackoverflow.com/a/394814/724039 – Luuk Nov 05 '22 at 19:57
  • Why you want to do that? - just curious. – Daniel Hao Nov 05 '22 at 20:52
  • @Luuk: thanks because point me to the right direction. – Joel Nov 06 '22 at 03:26

1 Answers1

0

Thanks to user @Luuk it show this post which tells some ways to use one line if statements, this helps me understand more about this code practice in python.

Joel
  • 1,805
  • 1
  • 22
  • 22