Menu
CoddyTech

Lists and Negative Indexes

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

Both languages offer ordered mutable lists, but Dart lists usually have a static element type and can be fixed-length, growable, or unmodifiable. Python lists hold references without an enforced generic element type and are normally growable. Python negative indexes count from the end; a negative Dart list index is out of range. Python slicing produces a shallow list copy and excludes the stop. Use add in Dart and append in Python to append one element. Python append returns None, so do not assign its result back to the list. Removing the first Python item with pop(0) returns that item.

Dart

void main() {
  final items = <int>[4, 8];
  items.add(12);
  print(items.last);
  print(items.sublist(0, 2));
}

Python

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

Porting trap

Dart last is a property; Python often uses index minus one. Porting the negative index in the other direction would fail.

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

Practice on your own: Online Python compiler