AlTs
AlTs

Reputation: 301

How to take element from list and make new list

My task is to make from string a list. Then move all elements from list to another list and convert it to string again. This is what I've done:

    def string_list(sentence: str) -> str:
        result = []
        sentence = sentence.split(" ")
        while sentence:
            for i in range(len(sentence)):
                tmp_var = sentence[i]
                result.append(tmp_var)
                sentence.remove(tmp_var)
        return " ".join(result)

print(string_list("Hey, how's it going?"))

But I got this error message: IndexError: list index out of range

Thank you in advance!

Upvotes: 1

Views: 106

Answers (5)

Aaditya Ura
Aaditya Ura

Reputation: 12679

If you want you can try list comprehension :

string_1="Hey, how's it going?"



origional_list=[i for i in string_1]
string_to_list=[i for i in origional_list if i!=',' and i!="'" and i!=' ']

print("String to list : {}".format(string_to_list))
list_to_string=("".join(origional_list))


print("list to String : {}".format(list_to_string))

output:

String to list : ['H', 'e', 'y', 'h', 'o', 'w', 's', 'i', 't', 'g', 'o', 'i', 'n', 'g', '?']
list to String : Hey, how's it going?

Upvotes: 1

user8715867
user8715867

Reputation: 23

Because at each iteration you remove one item of sentence so its length decreases. But your for loop still iterates through the initial sentence length.

Upvotes: 1

MaNKuR
MaNKuR

Reputation: 2704

Use list.pop to empty the input data

def string_list(sentence: str) -> str:
    result = []
    sentence = sentence.split(" ")
    if sentence:
        word = sentence.pop()
        result.append(word)
        while word:
            if not sentence:
                break
            word = sentence.pop()
            result.append(word)

    return ' '.join(result)

Upvotes: 1

def string_list(sentence):
    result = []
    sentence = sentence.split(" ")
    for word in sentence:
        result.append(word)

    sentence = []
    return " ".join(result)

print(string_list("Hey, how's it going?"))

I don't quiet understand why you are moving the words from one list to the other, but in python you can make use of the looping mechanism instead of using indices which may cause a hassle.

Hope my provided answer fixes your issue.

Upvotes: 1

Dharmesh Fumakiya
Dharmesh Fumakiya

Reputation: 2338

def string_list(str):
    result = []
    sentence = str.split(" ")
    for i in range(len(sentence)):
        result.append(sentence[i])
    return " ".join(result)

print(string_list("Hey, how's it going?"))

Upvotes: 1

Related Questions