3

I have the following PHP code, and for the life of me I can't think of a simple & elegant way to implement around the empty() function in python to check if the index is defined in a list.

$counter = 0;
$a = array();
for ($i=0;$i<100;$i++){
  $i = ($i > 4) ? 0 : $i;
  if empty($a[$i]){
    $a[$i]=array();
  }
  $a[$i][] = $counter;
  $counter++;
}

if I do

if a[i] is None

then I get index out of range. However I am aware of ways to do it in multiple steps, but that's not what I wanted.

James Lin
  • 25,028
  • 36
  • 133
  • 233
  • 1
    Look here http://stackoverflow.com/questions/473099/python-how-to-check-if-a-given-index-in-a-dict-exists-yet – Victor Jun 12 '12 at 00:57
  • Must it be implemented with an array? A `dict` would let you use `a.setdefault([])` and be done with it... – sarnold Jun 12 '12 at 00:57
  • the exception you get is exactly the way to go by enclosing it in a `try...catch` block. If you could show us your python code so far it may be even easier to help you out and probably find an easier way to implement your code – Toote Jun 12 '12 at 00:58

3 Answers3

3

PHP Arrays and Python lists are not equivalent. PHP Arrays are actually associative containers:

An array in PHP is actually an ordered map. A map is a type that associates values to keys. This type is optimized for several different uses; it can be treated as an array, list (vector), hash table (an implementation of a map), dictionary, collection, stack, queue, and probably more.

In Python, the map data structure is defined as a dictionary:

A mapping object maps hashable values to arbitrary objects. Mappings are mutable objects. There is currently only one standard mapping type, the dictionary.

The empty() function serve many purposes. In your use context, it is equivalent to the Python in operator:

>>> a = {}
>>> a[1] = "x"
>>> a[3] = "y"
>>> a[5] = "z"
>>> i = 3
>>> i in a
True
>>> i = 2
>>> i in a
False
vz0
  • 32,345
  • 7
  • 44
  • 77
0

In the event you were trying to do it with a list, you would have to actually set that index to none, otherwise the element wouldn't be there you'd possibly be trying to check an index past the end of the list.

>>> i = [None]
>>> i
[None]
>>> i = [None, None]
>>> i
[None, None]
>>> i[1] is None
True
njbooher
  • 612
  • 7
  • 18
0
# variable may not exsists    
if (variable in vars() or variable in globals()) and variable != "" and variable == False:
    pass
Vasin Yuriy
  • 484
  • 5
  • 13