A self-study guide for Python 3 compiled from the materials on this site. Primarily intended for those who want to learn the Python programming language from scratch.
Lists
// Immutable
val fruits = listOf("apple", "banana", "cherry")
println(fruits[0]) // apple
println(fruits.size) // 3
// Mutable
val items = mutableListOf("a", "b")
items.add("c")
items.remove("a")
println(items) // [b, c]
Maps
// Immutable
val capitals = mapOf("France" to "Paris", "Germany" to "Berlin")
println(capitals["France"]) // Paris
println(capitals.keys) // [France, Germany]
// Mutable
val scores = mutableMapOf("Alice" to 95, "Bob" to 87)
scores["Carol"] = 91
scores["Alice"] = 98
println(scores) // {Alice=98, Bob=87, Carol=91}
Sets
val uniqueNums = setOf(1, 2, 3, 2, 1)
println(uniqueNums) // [1, 2, 3]
val mutableSet = mutableSetOf("a", "b")
mutableSet.add("c")
mutableSet.add("a") // duplicate — ignored
println(mutableSet.size) // 3
Extension Functions on Collections
val numbers = listOf(3, 1, 4, 1, 5, 9, 2, 6)
println(numbers.sorted()) // [1, 1, 2, 3, 4, 5, 6, 9]
println(numbers.distinct()) // [3, 1, 4, 5, 9, 2, 6]
println(numbers.sum()) // 31
println(numbers.average()) // 3.875
println(numbers.count { it > 4 }) // 3
println(numbers.groupBy { it % 2 == 0 })
// {false=[3, 1, 1, 5, 9], true=[4, 2, 6]}
Sequences (Lazy Collections)
val result = (1..1_000_000)
.asSequence()
.filter { it % 3 == 0 }
.map { it * it }
.take(5)
.toList()
println(result) // [9, 36, 81, 144, 225]