Concepts / Creating Your Own Classes and Objects

Creating Your Own Classes and Objects

Lists are objects that bundle together data (the items they contain) and behavior (methods like append(), sort(), and __getitem__()).

  • Programming

A List Is More Than a Container

A list is an object. It bundles together the data it contains, such as its items, and the behaviors it can perform, such as adding an item, sorting its contents, or retrieving an item. When you create a list, you are creating an object with both data and actions.

containsprovidesprovidesprovideslist objectitemsdataappend()add an itemsort()rearrange items__getitem__()retrieve an item
What data does a list object contain, and what methods operate on that data?

Object-oriented programming centers on the idea that objects combine data with the actions they can perform. Lists provide a familiar example of this idea.

Watching List State Change

A list is mutable, which means its contents can change after the list is created. The append() method adds an item to the end of the list. The sort() method rearranges the existing items in order. Both methods modify the list object in place.

append('python')sort()['zebra', 'ant']initial list['zebra', 'ant','python']after append()['ant', 'python','zebra']after sort()
What does the list contain before and after calling append() and sort(), and how does its state change step by step?

Following Two List Methods

Trace the list after it is created, after append('python'), and after sort().

Initial state: The list begins with the items 'zebra' and 'ant'.

Append: append('python') adds 'python' to the end, so the list now contains three items.

Sort: sort() rearranges the strings alphabetically, placing 'ant' first, 'python' second, and 'zebra' third.

The final list is ['ant', 'python', 'zebra'].

stuff = list() stuff.append('zebra') stuff.append('ant') stuff.append('python') stuff.sort() print(stuff)

Methods as Object Behaviors

A method is an action or behavior that an object can perform. In stuff.append('python'), append() is being called on the list object referred to by stuff. The method changes that object's contents by adding a new item at the end.

In stuff.sort(), sort() is also called on the list object. Instead of adding an item, it rearranges the items into order. For strings, the source explains this as alphabetical order; for numbers, it is numerical order.

invokesmodifiesmethod callstuff.append('python')append()add to endupdated listone more item
How does control move from a list method call to the resulting change in the list contents?

Three Ways to Retrieve an Item

A list item can be retrieved with square bracket syntax or with the list's __getitem__() method. The source presents three equivalent forms for retrieving the item at position 0: stuff[0], stuff.__getitem__(0), and list.__getitem__(stuff, 0).

retrievesretrievesretrievesstuff[0]position 0first itemsame resultstuff.__getitem__(0)position 0list.__getitem__(stuff,0)position 0
How do the three retrieval forms map to the same item position?
python
FormWhat it showsRecommended use
stuff[0]Retrieves the item at position 0Standard and most convenient syntax
stuff.__getitem__(0)Calls the special method directly on the list objectMore explicit view of the list behavior
list.__getitem__(stuff, 0)Calls the method on the list class and passes stuff as the first parameterMost verbose form

Positions and Retrieved Items

The number inside square brackets identifies the position of the item to retrieve. In the source example, position 0 means the first item. __getitem__(0) performs the same retrieval when called explicitly, so the index and the returned item remain connected across all three syntaxes.

selectsreturns0indexfirst itemposition 0retrieved item__getitem__(0)
How does a numeric index identify a specific item inside a list, and what does __getitem__() return?

Mistakes Beginners Make

  • Treating a list as only passive data

    A list bundles its items with behaviors that operate on those items.

    Fix: When reading list code, identify both the current data and the method being called.

  • Forgetting that append() changes the list

    append() adds an item to the end and modifies the list in place.

    Fix: Record the list's new contents immediately after the append() call.

  • Expecting sort() to leave the order unchanged

    sort() rearranges the items into order.

    Fix: Trace the list again after sorting; strings are arranged alphabetically and numbers numerically.

  • Assuming the explicit retrieval forms produce different items

    All three forms retrieve the item at position 0.

    Fix: Recognize square brackets as the standard, convenient syntax for the same behavior.

Check Your Understanding

What do you think happens?

A list starts as ['zebra', 'ant']. After append('python') and then sort(), what will the final list contain?

  • ['zebra', 'ant', 'python']
  • ['ant', 'python', 'zebra']
  • ['python', 'ant', 'zebra']
Reveal answer

Answer: ['ant', 'python', 'zebra']

append() first adds 'python' to the end. sort() then rearranges the strings alphabetically.

EASY

For a list named stuff, write the three equivalent expressions that retrieve the item at position 0. Then explain which form is normally preferred and why.

Hints
  • Start with square bracket syntax.
  • Use __getitem__() as a method on stuff.
  • For the most verbose form, call __getitem__() on list and pass stuff as the first parameter.

From Built-In Objects to Your Own

Lists make object-oriented programming concrete. The list's items are its data, while append(), sort(), and __getitem__() are behaviors available through the list object. Method calls can modify the object in place, as append() and sort() do. Item retrieval can be written with square brackets or with the corresponding __getitem__() forms, but square brackets are the standard choice. This perspective prepares you to create objects with your own data and methods.

Key Takeaways

  • A list is an object that combines its item data with methods that operate on that data.
  • append() adds an item to the end of a list, while sort() rearranges items in order.
  • append() and sort() modify the existing list object in place.
  • stuff[0], stuff.__getitem__(0), and list.__getitem__(stuff, 0) retrieve the same item at position 0.
  • Understanding lists as objects provides a foundation for creating objects with custom data and methods.