Read-only Lists and Mutation
Lesson 12 of 48 in Coddy's Python for Kotlin Developers course.
Kotlin separates List and MutableList interfaces; a read-only view is not necessarily a deeply immutable object. Python's ordinary list exposes mutation directly and can contain objects of different types. Python negative indexes count from the end, unlike Kotlin indexed access. A slice creates a new outer list. Kotlin MutableList.add reports a Boolean result; Python append mutates and returns None.
Kotlin
fun main() {
val items = mutableListOf(4, 8)
println(items.add(12))
println(items.last())
}Python
items = [4, 8]
print(items.append(12))
print(items[-1])Porting trap
Do not assign the result of append back to the list. To enforce an immutable positional collection in Python, consider a tuple, while remembering its nested objects can still mutate.
Complete the task in its editable modules. The locked driver.py supplies execution; keep the required API names.
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 Kotlin Developers
1From Kotlin to Python
Run Your First Python ProgramPrint and String TemplatesVal, Var, and Python NamesDivision and Integer WidthSuites and Block ScopeRecap: Rewrite a Receipt4Iteration and Transformations
Ranges and Loop BindingsEntries and withIndexUpdates and Loop ControlCollection PipelinesRecap: Build a Ranking2Values and Decisions
Nullable Types and NoneEquality and IdentityBoolean Conditions and orIf Expressions and ElifRecap: Eligibility Rules3Collections and Shared State
Read-only Lists and MutationPair and Tuple UnpackingMap Lookup and Missing KeysShallow Copies and SetsRecap: Clean an Inventory6Input, Errors, and Modules
Console Input and FormattingExceptions and Resource ScopeImports and Entry PointsStatic Types and AnnotationsRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler