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
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 Dart Developers
1From Dart to Python
Run Your First Python ProgramInterpolation and printvar, final, and Python NamesFloor Versus TruncationBraces and Block ScopeRecap: Rewrite a Receipt4Iteration and Transformations
for-in and rangeentries and enumerateLoop Updates and continuewhere, map, and List BuildingRecap: Build a Ranking2Values and Decisions
Null Safety and NoneList Equality ChangesConditions and Null DefaultsTernaries and elifRecap: Eligibility Rules3Collections and References
Lists and Negative IndexesRecords and Tuple UnpackingMap Lookups and KeyErrorSets and Shared ObjectsRecap: Clean an Inventory6Reliable Python Programs
stdin and Exact Formattingon, catch, finally, and withLibraries and Import ExecutionStatic Types Versus HintsRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler