0
votes

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 way to do this with a list nested inside a dictionary, like this PHP equivalent..

$array['associative'][] = 'value';
4
-0. This has a very low google difficulty level. This is covered official python tutorial (docs.python.org/tutorial). Appending to a list is shown in section 3.1.4 and mentioned again in section 5.1. - Steven Rumbalski
This has very low tab completion difficulty ;). - Bi Rico

4 Answers

6
votes
my_list.append(value)

or

my_dict[key].append(value)
2
votes

The best way for dict of lists is:

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

that is equivalent for

if not key in 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!

1
votes

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

 myList.append(value)
1
votes
mylist.append(value)

See "pydoc list".