How can i write for&if-else statement using only one line?

Question:

  • Make List a String: Let’s make the list ["Life", "is", "too", "short"] into a "Life is too short" string and print it out.

First, Let me tell you i know the way to solve the problem using join() method.

I wanted to solve this using another method, and i used for statement as below.

liszt = ['Life', 'is', 'too', 'short']
restr = ''
for i in liszt: restr += i+' ' if liszt.index(i) != 3 else restr += i
print(restr)

How can i correct this in valid syntax?
or… is there any simpler way to code this than mine?

At that time, I intended to express same thing as below using one line. But editor told me it’s invalid syntax.

liszt = ['Life', 'is', 'too', 'short']
restr = ''
for i in liszt:
    if liszt.index(i) != 3:
        restr += i+' '
    else:
        restr += i
print(restr)

Asked By: benu

||

Answers:

you can use join function for exactly this purpose

print(" ".join(liszt))
Answered By: ashish singh

As others have mentioned, one-liners aren’t always better/faster/more readable. Here’s a solution using functools.reduce.

from functools import reduce
liszt = ['Life','is','too','short']
restr = reduce(lambda x,y: x + ' ' + y, liszt)
print(restr)

Another without importing:

restr = ''
for i,word in enumerate(liszt): restr += word + (' ' if i != len(liszt)-1 else '')

Another one using the walrus operator:

restr = ''
[restr := restr + (' ' if i else '') + word for i,word in enumerate(liszt)]

Or using the indexing in your question:

restr = ''
for i in liszt: restr += i+(' ' if liszt.index(i) != len(liszt)-1 else '')
Answered By: Gábor Fekete

You can use conditional assignment inside a one-line for loop like this:

for i in liszt: restr += i + ' ' if liszt.index(i) != 3 else i
Answered By: tobifasc

using recurssion here is code in one liner

nstring = "this is a program running on computer"
nstring = "this is a program running on computer".split()
print(nstring)
# output -> ['this', 'is', 'a', 'program', 'running', 'on', 'computer']
def new_join_method(string): return '' if (len(string) == 0) else f"{string[0]} {func(string[1:])}".strip()
 
solution = new_join_method(nstring)
print(solution)
# output. --> 'this is  a  program  running  on  computer'
Answered By: sahasrara62

You could use str.translate() method to remove the unwanted characters from the strings in liszt by calling str.maketrans to create a translation table to remove square brackets, commas and quotes.

import string

liszt = ['Life', 'is', 'too', 'short']
restr = str(liszt).translate(str.maketrans("", "", "[],''"))
print(restr)

Output:

Life is too short
Answered By: Jamiu Shaibu
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.