I am new to Python but not new to PHP. I've started porting PHP APIs to Python hoping to learn the Python language along the way, currently trying to grasp List, Dict, Set, Tuple. I tried writing PHP's array_push() in Python:
def array_push(array: list | dict, *args: any) -> int:
if isinstance(array, list):
for arg in args:
# i wonder why list.append() doesn't take *args
array.append(arg)
return len(array)
elif isinstance(array, dict):
# wouldn't surprise me if there's a significantly faster way to do this,
# but this the first solution I could think of that worked
key = -1
# i tried using key = max(array.keys()), but that breaks if the dict has string keys..
for existingkey in array.keys():
if isinstance(existingkey, int) and existingkey > key:
key = existingkey
for arg in args:
# loop should not be needed because we already started with the highest key?
# while key in array:
key += 1
array[key] = arg
return len(array)
else:
raise TypeError(
"array_push() expects a list or dict as first argument, got " + str(type(array)))
and some tests:
l = ["foo", "bar", "baz"]
array_push(l, 1, "foo", 9, 9)
print(l) # prints ['foo', 'bar', 'baz', 1, 'foo', 9, 9]
d = {5: "five already exist, terrific..", 6: "as does 6..",
"string key": "it has a string key too", 2: "2 comes after 5, hurray"}
array_push(d, 1, "foo", 9, 9)
print(d) # prints {5: 'five already exist, terrific..', 'string key': 'it has a string key too', 2: '2 comes after 5, hurray', 6: 1, 7: 'foo', 8: 9, 9: 9}
array_push(5, 5) # TypeError: array_push() expects a list or dict as first argument, got <class 'int'>
["foo", "bar", "baz"].extend([1, "foo", 9, 9]) => ['foo', 'bar', 'baz', 1, 'foo', 9, 9]
\$\endgroup\$array.extend(args);
instead of that first loop, but i will keep the original code in the question for now, in case someone has started reviewing ^^ \$\endgroup\$