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
BeginnerRead 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__")
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Python for PHP Developers
1From PHP to Python
Run Your First Python ProgramEcho, Strings, and printVariables Without Dollar SignsDivision and Numeric TextIndentation and SuitesRecap: Rewrite a Receipt4Iteration and Transformations
Foreach and rangeKeys, Items, and enumerateWhile Without IncrementFilters and Sort KeysRecap: Build a Ranking2Values and Decisions
Null, None, and Missing KeysStrict Equality Is Not isThe Zero String TrapElif and Value SelectionRecap: Eligibility Rules3Arrays and Python Collections
PHP Arrays and Python ListsDestructuring and TuplesKeys, Null, and getArray Copies and List AliasesRecap: Clean an Inventory6Input, Errors, and Modules
CLI Input and Exact OutputConversion Errors and CleanupImports Instead of requireType Hints Are Not PHP TypesRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler