Skip to content

Learning Python: Day 4

Chapter 3: Introducing Lists

What is a list?

  • list – collection of items in a particular order
  • can include letters, numbers, and names of family members
  • make the name of your lists plural: letters, numbers, names
  • square brackets ([]) indicate a list and commas separate individual elements in the list

bicycles.py

bicycles = [‘trek’, ‘cannondale’, ‘redline’, ‘specialized’]

print(bicycles)

[‘trek’, ‘cannondale’, ‘redline’, ‘specialized’]

Accessing elements in a list

  • lists are ordered collections, so you can access any element in a list by telling Python the position to index of the item desired
  • to access an element in a list, write the name of the list followed by the index of the item enclosed in square brackets

bicycles

bicycles = [‘trek’, ‘cannondale’, ‘redline’, ‘specialized’]

print(bicycles[0])

trek

  • Python returns a single item from a list without square brackets
  • use string methods on any element in this list
  • for example, make ‘trek’ more presentable with the title() method

bicycles = [‘trek’, ‘cannondale’, ‘redline’, ‘specialized’]

print(bicycles.title[0])

Trek

Index positions start at 0, not 1

  • first item is at position 0, second item is at position 1

bicycles = [‘trek’, ‘cannondale’, ‘redline’, ‘specialized’]

print(bicycles[1])

print(bicycles[3])

cannondale

specialized

  • index -1 returns last item in the list

bicycles = [‘trek’, ‘cannondale’, ‘redline’, ‘specialized’]

print(bicycles[-1])

specialized

Using individual values from a list

  • can use f-strings to create a message based on a value in a list
  • let’s pull the first bicycle from the list and compose a message using that value:

bicycles = [‘trek’, ‘cannondale’, ‘redline’, ‘specialized’]

message = f”My first bicycle was a {bicycles[0].title()}.”

print(message)

My first bicycle was a Trek.

Modifying, adding, and removing elements

  • dynamic – most lists will be dynamic, meaning elements will be added and removed from lists you’ve built as your program runs its course

Modifying elements in a list

  • syntax for modifying an element in a list is similar to the syntax for accessing an element in a list
  • to change an element, use the name of the list followed by the index of the element you want to change, then provide the new value you want that item to have

motorcycles.py

motorcycles = [‘honda’, ‘yamaha’, ‘suzuki’]

print(motorcycles)

[‘honda’, ‘yamaha’, ‘suzuki’]

motorcycles[0] = ‘ducati’

print(motorcycles)

[‘ducati’, ‘yamaha’, ‘suzuki’]

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *