Menu
CoddyTech

Array Methods and Lists

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

A Python list is the usual counterpart of a Ruby array: it is ordered, mutable, growable, and stores object references. Both support negative indexes. Python slicing excludes the stop index, corresponding to the intent of a Ruby exclusive range slice. Indexing beyond a Ruby array commonly returns nil; Python indexing raises IndexError. Python slices clip oversized bounds. Ruby push and << return the modified array, which supports chaining. Python append mutates the list but returns None. The challenge also uses pop(0) to remove and return the first item, analogous to Ruby shift.

Ruby

items = [4, 8]
saved = items.push(12)
p saved

Python

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

Porting trap

Do not assign the result of Python append back to your list. You would replace the list reference with None.

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 Ruby Developers

Practice on your own: Online Python compiler