Accessing Elements
Part of the Fundamentals section of Coddy's Kotlin journey. Lesson 68 of 93.
Now that you can create lists, you need to know how to retrieve individual elements from them. Kotlin uses index-based access, where each element has a position number starting from 0.
Use square brackets with the index to access an element:
val colors = listOf("Red", "Green", "Blue")
println(colors[0]) // Red
println(colors[1]) // Green
println(colors[2]) // BlueYou can also use the first() and last() functions for quick access to the endpoints:
val numbers = listOf(10, 20, 30, 40)
println(numbers.first()) // 10
println(numbers.last()) // 40To find out how many elements a list contains, use the size property. Since indexing starts at 0, the last valid index is always size - 1:
val fruits = listOf("Apple", "Banana", "Cherry")
println(fruits.size) // 3
println(fruits[fruits.size - 1]) // CherryBe careful not to access an index that doesn't exist - trying to access fruits[5] in a 3-element list will cause an error.
Challenge
MediumWrite a function getFirstAndLast that takes a list of integers and returns a string containing the first and last elements.
Use the appropriate list access methods to retrieve the first and last elements, then combine them into a formatted string.
Parameters:
numbers(List<Int>): A list of integers with at least one element
Returns: A string in the format "First: X, Last: Y" where X is the first element and Y is the last element.
Input constraints: The input list is nonempty.
Try it yourself
fun getFirstAndLast(numbers: List<Int>): String {
// Write code here
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorAugmented AssignmentComparison OperatorsRecap - Simple Math7Basic IO
Println FunctionString TemplatesReadLine InputType ConversionRecap - Years Until RetirementRecap - True or False10Functions
Declare A FunctionParameters And ArgumentsReturn ValuesNamed ArgumentsDefault ValuesSingle Expression FunctionsRecap - Sigma FunctionRecap - Validation Function2Variables
Val vs VarType InferenceNumbersStringBooleanNaming ConventionsRecap - Initialize Variables5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Logical Operators Part 3Ternary With If ExpressionRecap - Simple Logic8Bill Split Calculator
Welcome MessageGetting Input3Nullability
What Is Null SafetyNullable TypesSafe Call OperatorElvis OperatorFunction Challenge BasicsNot Null AssertionRecap - Safe Access6Decision Making
If StatementIf - ElseIf As An ExpressionWhen ExpressionWhen With RangesRecap - Simple Calculator9Loops
For LoopWhile LoopDo-While LoopBreakContinueRanges In LoopsNested LoopRecap - FactorialRecap - Dynamic Input12Lists Basics
List vs MutableListAccessing ElementsModifying ListsList MethodsPair And TripleRecap - Product ListRecap - Reversed ListPractice on your own: Kotlin playground