Skip to content Skip to sidebar Skip to footer

Quickly Append Value To A List

PHP has a really quick way to append a value to an array: $array[] = 'value'; What is the easiest way to do this in python without needing an index number? Also, is there an easy

Solution 1:

my_list.append(value)

or

my_dict[key].append(value)

Solution 2:

The best way for dict of lists is:

my_dict.setdefault(key,list()).append(value)

that is equivalent for

ifnotkeyin my_dict:
    my_dict[key] = list()
nested_list = my_dict[key]
nested_list.append(value)

Thist is safe when my_dict doesnt have any list at key.

In earlier proposed variant:

my_dict[key].append(value)

which is equivalent for

nested_list = my_dict[key]
nested_list.append(value)

KeyError will be raised if my_dict has no item at key

But if my_dict[key] has no 'append' method AttributeError would be raised in both variants

UPD (important!): in construction like my_dict.setdefault(key,list()) a list instance is created even if my_dict has key!

Solution 3:

How about the append() list method? e.g.,

 myList.append(value)

Solution 4:

mylist.append(value)

See "pydoc list".

Post a Comment for "Quickly Append Value To A List"