jkwhite
jkwhite

Reputation: 320

Adding Booleans to a list results in a TypeError

I've created a blank list and am attempting to add a boolean to that list. However, I'm getting a few different errors. I'm fairly new to Python so any explanations would be helpful.

What I'm attempting to do is:

    new_list=[]
    new_list[0] = True #ERROR: TypeError: 'type' object does not support item assignment

or

    new_list=[]
    new_list.append(True) #ERROR: TypeError: descriptor 'append' requires a 'list' object but received a 'bool' 

More precisely, I'm attempting to send this through a loop

    new_list=[]
    for arg in args:
        if (arg == 'foo' or arg == 'bar'):
            new_list[arg] = True

Obviously, the error in the first block is because the list is not accepting the boolean that's being passed. The second is also providing a similar error. However, because this is a blank list, shouldn't this accept any input?

I've attempted to follow this however, it looks like even this may not work.

Thanks in advance.

Upvotes: 0

Views: 403

Answers (3)

pyzor
pyzor

Reputation: 191

new_list = [] #creates a new list
new_bool_list = [True]*10 # creates a list size 10 of booleans

In python you don't have to set the size of the list, you can create an empty list and add onto it.

new_list = []
new_list.append(True)
print(new_list)

--------------
output:
[True]

for your loop question it depends on your arguments. new_list[arg] = True is generally how you set a value in a dictionary (HashMap in other languages). I think you'd be better off researching those for your intended question.

Upvotes: 0

Stephen Collins
Stephen Collins

Reputation: 903

If you want to track the name of the arg if it is either "bar" or "foo", you could try something like this:

    list = []
    for arg in args:
        if arg == 'foo' or arg == 'bar':
            argDic = { arg: True }
            list.append(argDic)

    print(list)
    # [{'foo': True}, {'bar': True}]

Upvotes: 0

Omri Attiya
Omri Attiya

Reputation: 4037

new_list = [] creates an empty list. In your first try, you are trying to access new_list[0], but the first place in the list ([0]) does not exist, because the list is empty.

When you want to add values to the list you need to use append. So your second try is correct, you should use: new_list.append(True), but the first line where you define the empty list is wrong. You used new_list[] instead of new_list = [].

As for the usage of new_list[], it's a syntax error. If you want to define an empty list you should use new_list = [] or new_list = list().

Upvotes: 3

Related Questions