Menu
Coddy logo textTech

List Properties: first & last

Part of the Logic & Flow section of Coddy's Dart journey — lesson 1 of 65.

When working with lists, you often need to access the first or last element. Instead of using index numbers like [0] or [list.length - 1], Dart provides two convenient properties that make this much simpler.

The .first property gives you the first element in a list, while the .last property gives you the last element. These properties are more readable and less error-prone than calculating index positions.

List<String> planets = ['Mercury', 'Venus', 'Earth', 'Mars'];

String firstPlanet = planets.first;   // 'Mercury'
String lastPlanet = planets.last;     // 'Mars'

These properties work with any non-empty list and automatically handle the index calculations for you. This makes your code cleaner and easier to understand when you need to work with the elements at the beginning or end of your lists.

challenge icon

Challenge

Easy

Create a program that analyzes a music playlist by accessing the first and last songs. Your program should:

  1. Read a string input representing the playlist name
  2. Read multiple string inputs representing song titles (the input will end when you receive an empty string)
  3. Use the .first property to get the first song in the playlist
  4. Use the .last property to get the last song in the playlist
  5. Print the playlist analysis in the exact format shown below

For example, if the playlist name is "My Favorites" and the songs are "Bohemian Rhapsody", "Imagine", "Hotel California", your program should output:

Playlist: My Favorites
Total songs: 3
Opening track: Bohemian Rhapsody
Closing track: Hotel California

Your program must handle playlists with any number of songs and use the .first and .last properties to access the opening and closing tracks.

Cheat sheet

Use .first and .last properties to access the first and last elements of a list:

List<String> planets = ['Mercury', 'Venus', 'Earth', 'Mars'];

String firstPlanet = planets.first;   // 'Mercury'
String lastPlanet = planets.last;     // 'Mars'

These properties are more readable than using index numbers like [0] or [list.length - 1] and work with any non-empty list.

Try it yourself

import 'dart:io';

void main() {
  // Read playlist name
  String? playlistName = stdin.readLineSync();
  
  // Read songs until empty string
  List<String> songs = [];
  String? song;
  while ((song = stdin.readLineSync()) != null && song!.isNotEmpty) {
    songs.add(song);
  }
  
  // TODO: Write your code below
  // Use songs.first and songs.last to get the opening and closing tracks
  
  // Output the playlist analysis
  print("Playlist: $playlistName");
  print("Total songs: ${songs.length}");
  // Print opening and closing tracks here
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow