Why Does List.Append Evaluate to False in a Boolean Context

Why does list.append evaluate to false in a boolean context?

Most Python methods that mutate a container in-place return None -- an application of the principle of Command-query separation. (Python's always reasonably pragmatic about things, so a few mutators do return a usable value when getting it otherwise would be expensive or a mess -- the pop method is a good example of this pragmatism -- but those are definitely the exception, not the rule, and there's no reason to make append an exception).

Add an element to a list, the output is none

Adding to the replies that you got, if it is the list b that needs to be updated but not the list a, you should proceed as such:

a =[1,2,3]
b = list(a)
b.insert(1,20)
print(a, b)

List append() in for loop raises exception: 'NoneType' object has no attribute 'append'

The list.append function does not return any value(but None), it just adds the value to the list you are using to call that method.

In the first loop round you will assign None (because the no-return of append) to a, then in the second round it will try to call a.append, as a is None it will raise the Exception you are seeing

You just need to change it to:

a = []
for i in range(5):
# change a = a.append(i) to
a.append(i)
print(a)
# [0, 1, 2, 3, 4]

list.append is what is called a mutating or destructive method, i.e. it will destroy or mutate the previous object into a new one(or a new state).

If you would like to create a new list based in one list without destroying or mutating it you can do something like this:

a=['a', 'b', 'c']
result = a + ['d']

print result
# ['a', 'b', 'c', 'd']

print a
# ['a', 'b', 'c']

As a corollary only, you can mimic the append method by doing the following:

a = ['a', 'b', 'c']
a = a + ['d']

print a
# ['a', 'b', 'c', 'd']

Python: how to append to a list in the same line the list is declared?

list.append is an in-place method, so it changes the list in-place and always returns None.

I don't think you can append elements while declaring the list. You can however, extend the new list by adding another list to the new list:

names = ['john', 'mike', 'james'] + ['dan']
print(names)


Related Topics



Leave a reply



Submit