Objects in Lists

Objects in Lists

Objects go into lists like any other value, and the patterns from the loops section apply unchanged — accumulate, filter, search:

class Song:
    def __init__(self, title, seconds):
        self.title = title
        self.seconds = seconds

playlist = [
    Song("Intro", 90),
    Song("Anthem", 240),
    Song("Outro", 130),
]

total = 0
for song in playlist:
    total += song.seconds
print(total)

Output:

460

The only new element is reading an attribute (song.seconds) where a plain loop read a list element or a dictionary value. Filtering works the same way:

long_titles = [song.title for song in playlist if song.seconds > 100]
print(long_titles)

Output:

['Anthem', 'Outro']

This list-of-objects shape replaces the list-of-dictionaries shape from the dictionaries section when the items deserve methods and named structure.

Exercise

The starter code defines Song and a playlist.

  1. Define a function named longest_song with one parameter, songs (a non-empty list of Song objects).
  2. It returns the title of the song with the most seconds.

For the playlist above, longest_song(playlist) returns "Anthem".

Run your code to see the output, then press Submit.

Tests

import unittest


class TestLongestSong(unittest.TestCase):
    def test_middle_song_is_longest(self):
        songs = [Song("Intro", 90), Song("Anthem", 240), Song("Outro", 130)]
        self.assertEqual(longest_song(songs), "Anthem")

    def test_single_song(self):
        self.assertEqual(longest_song([Song("Solo", 10)]), "Solo")

    def test_last_song_is_longest(self):
        songs = [Song("A", 10), Song("B", 20), Song("C", 30)]
        self.assertEqual(longest_song(songs), "C")
class Song:
    def __init__(self, title, seconds):
        self.title = title
        self.seconds = seconds


def longest_song(songs):
    longest = songs[0]
    for song in songs:
        if song.seconds > longest.seconds:
            longest = song
    return longest.title


playlist = [
    Song("Intro", 90),
    Song("Anthem", 240),
    Song("Outro", 130),
]
print(longest_song(playlist))
Solution hidden. Give it a real try first.

Sign in to join the discussion.

No comments yet. Be the first to ask a question.

main.py
Console
Press Run to execute your code, or Submit to test and complete this problem.