Unable to add more than one string to a list

917 views python
1

I started to make a program where you can add a list and than search through it. It was all going fine until an error kept showing up.

_list = []
def variables(variable):
    return variable.title()

while True:
    inputt = input("\nPrint c to create/add to a program\nand s to search for"
                   " something that is in that list, enter 'q' when u ready")
    if inputt == 'c':
        while True:
            create_something = input("What is the item you want to add your list")
            _list.append(create_something)
            _list = str(_list)
            print("This is your list so far\n" + _list)
            if create_something == 'q':
                print("This is yo' list so far")
                break
    elif input == 's':
        print("cool")

When I try to add more than one item to the list it says that 'str' object has no attribute 'append'.

answered question

This line _list = str(_list) overrides your list object with a string object, You can't append anything to a string because there is no such method for string objects.

You change your list to a string in the line _list = str(_list).

I have that; in line 12

Also note there's a typo in the elif input == 's': line—it should be elif inputt == 's':. The way it is, the condition will never evaluate to True.

2 Answers

11

This line converts _list into a string, and it's no longer a list anymore:

_list = str(_list)

So when your loop executes the second time, it tries to run _list.append() and throws the error you reported.

posted this
4

append works only on list and not on string. If you want to convert to string to just print, then consider using str(_list) just for the print or use join method.

Here is an example using join :

_list = []
def variables(variable):
    return variable.title()


while True:
    inputt = input("\nPrint c to create/add to a program\nand s to search for something that is in that list, enter 'q' when u ready")
    if inputt == 'c':
        while True:
            create_something = input("What is the item you want to add your list")
            _list.append(create_something)
            print("This is your list so far\n" + ''.join(_list))
            if create_something == 'q':
                print("This is yo' list so far")
                break

    elif input == 's':
        print("cool")

Leaving _list as list, however while printing them - use join to print them as string.

Print c to create/add to a program
and s to search for something that is in that list, enter 'q' when u ready'c'
What is the item you want to add your list'foo'
This is your list so far
foo
What is the item you want to add your list' bar'
This is your list so far
foo bar
What is the item you want to add your list' baz'
This is your list so far
foo bar baz

posted this

Have an answer?

JD

Please login first before posting an answer.