Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?

Introduction to Lists

We just talked about Python's basic data types, string, integer and floating point objects. Python variables, then are like labels for objects; they're a way to refer to them.

But when writing real programs, one soon wishes there was more. For example, when there are lots of objects, which pretty much every program has. This gets tedious fast:

dog1 = 'maru'
dog2 = 'phoebe'
dog3 = 'pebbles'

print(dog1.capitalize())
print(dog2.capitalize())
print(dog3.capitalize())

print(f'The first dog is {dog1}')

All that repetitive code is no good. In fact, there's a programmer saying, "keep your code DRY" (Don't Repeat Yourself). The solution lies in re-thinking how we've organized this code: Instead of thinking of it as working with three dog objects, see it as working with a list of dogs. Python makes it easy to think about it this way with the list type:

dogs = ['maru', 'phoebe', 'pebbles']

for dog in dogs:
    print(dog.capitalize())

print(f'The first dog is {dogs[0]}')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.