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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With