2

In some languages, like php, you don't need to manually initialize each dimension of a multidimensional array. You just specify the key path, and the language will automatically initialize the sub arrays if needed.

For example, in php I can just do

$foo = array();
$foo['sub1']['sub2']['sub3'] = 5;

Instead of having to manually initialize each level of sub array

$foo = array();
$foo['sub1'] = array();
$foo['sub1']['sub2'] = array();
$foo['sub1']['sub2']['sub3'] = 5;

I know that python offers this convenience as well I've seen python code that appears equivalent, so I figure there's a name for this feature.

What is the name of this feature?

goat
  • 31,486
  • 7
  • 73
  • 96
  • Are you by any chance talking about dictionaries in Python? http://docs.python.org/tutorial/datastructures.html – tabchas Jun 13 '12 at 17:05
  • 1
    A duplicate of: http://stackoverflow.com/questions/651794/whats-the-best-way-to-initialize-a-dict-of-dicts-in-python – Tisho Jun 13 '12 at 17:06
  • 2
    This isn't particularly language agnostic, when the meaning of the word "array" varies considerably between languages. – Jon Skeet Jun 13 '12 at 17:07
  • 2
    In Perl it's called autovivification. – Mark Dickinson Jun 13 '12 at 17:11
  • Autovivification is an answer! someone post it. – goat Jun 13 '12 at 17:14
  • 1
    Done. (11 more characters to go ...) – Mark Dickinson Jun 13 '12 at 17:16
  • It's worth mentioning that the question is wrong: Python _doesn't_ offer this convenience; if you want it, you can build it yourself in a few lines of code, but it's not directly built-in, which means there's no standard name for it. Perl, on the other hand, does have a name for it (as Mark Dickinson says), and that's as close to a language-agnostic name as you're likely to find. – abarnert Jun 13 '12 at 17:22
  • @abarnert: Good point; I've updated my answer. – Mark Dickinson Jun 13 '12 at 17:36
  • @abarnet, thanks. I had seen it a few times in python code, and assumed it was native. – goat Jun 13 '12 at 17:54
  • @rambocoder: The fact that it's not native, and not even built into the standard library, is actually intentional. Guido believes it just confuses people about how dicts work, and anyone who can't figure out how to implement it by using defaultdict recursively shouldn't be using it. – abarnert Jun 13 '12 at 18:12

1 Answers1

3

I believe the corresponding feature in Perl is called autovivification. As the wikipedia page points out, Python dictionaries don't have this feature by default, but it's easy to build something that behaves this way by making use of collections.defaultdict. See this recent blog post for some ideas.

Mark Dickinson
  • 29,088
  • 9
  • 83
  • 120