Menu
CoddyTech

PHP Arrays and Python Lists

Lesson 12 of 48 in Coddy's Python for PHP Developers course.

A PHP array is an ordered map that can mix integer and string keys. Python separates indexed sequences (list) from mappings (dict). A Python list uses contiguous zero-based positions, and a negative index counts from the end. Slices exclude their stop position and create a new outer list. PHP $items[] = value appends; Python uses items.append(value). The method changes the list and returns None, unlike PHP array_push, which returns a count.

PHP 8.3

<?php
$items = [4, 8];
echo array_push($items, 12), "\n";
echo $items[2], "\n";

Python

items = [4, 8]
print(items.append(12))
print(items[-1])

Porting trap

Do not translate a negative PHP array key into a Python list index: PHP key -1 is an actual map key, while Python index -1 means the last element.

Complete the task in the editable Python files. Keep the required function and class names; the locked driver.py supplies execution.

challenge icon

Challenge

Beginner

Read four integers on four lines. Create a list from the first three, append the fourth, then remove the first item with pop(0). Print the removed integer, the resulting last item, and the first two items of the resulting list on separate lines. Print the last line in Python list format, such as [2, 3]. Values range from -20 to 20.

Print only the requested output, with a newline after each line. Keep the supplied input scaffold. No loops or functions are needed.

Your code goes in main.py. The locked driver.py starts your program and cannot be edited.

Try it yourself

# Starts the program in main.py. Edit main.py to solve the challenge.
from runpy import run_module

run_module("main", run_name="__main__")
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Python for PHP Developers

Practice on your own: Online Python compiler