Skip to content

Chapter 3

Jarlin Almanzar edited this page Oct 25, 2019 · 2 revisions

Introducing Lists

A list is a collection of items in a particular order
They can include a list that includes letters of the alphabet, digits from 0-9, names, dates, and so on.

Example of a list

#bicycle brands
bicycles = ['trek', 'cannondale', 'redline', 'specialized']
print(bicycles)

Accessing an Element in a List

bicycles = ['trek', 'cannondale', 'redline', 'specialized']
print(bicycles[0])
# Will print trek, the first value of the list

Index Positions start at 0, Not 1

list[-1] would return the value in the last index of a list
In this case bicycles[-1] would return specialized

#EX: Using Index in a list 
bicycles = ['trek', 'cannondale', 'redline', 'specialized']
msg = f"My first bike was a {bicycles[0].title()}"
print(msg)

Modifying Elements in a list

Overwrite a value

motorcycles = ['honda', 'yamaha', 'suzuki']
motorcycles[0] = 'ducati'
print(motorcycles)
# it will print ['ducati', 'yamaha', 'suzuki']

Appending to the end of a list

motorcycles.append('ducati')
print(motorcycles)

Add to a list dynamically

motorcycles = []
motorcycles.append('honda')
motorcycles.append('yamaha')
motorcycles.append('suzuki')
print(motorcycles)

Inserting Elements in a list

motorcycles.insert(0, 'ducati')

Removing an Item from a list, del statement

motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)
del motorcycles[0]
print(motorcycles)

Removing an Item Using the pop() method

# pop() removes the last item in a list, but it lets you work an item after removing it
motorcycles = ['honda', 'yamaha', 'suzuki']
pop_mtr = motorcycles.pop()
print(motorcycles)
print(pop_mtr)

Removing an Item by Value

# remove()
motorcycles = ['honda', 'yamaha', 'suzuki']
motorcycles.remove('honda')
print(motorcycles)

Sorting a list

# sort()
cars= ['bmw', 'audi', 'toyota', 'subaru']
cars.sort()
print(cars)

Sorting and reversing a list

# sort()
cars= ['bmw', 'audi', 'toyota', 'subaru']
cars.sort(reverse=True)
# or cars.reverse() but not sorted
print(cars)

Temporarily sort a list

# sorted() returns the list in order without affecting the original list
cars= ['bmw', 'audi', 'toyota', 'subaru']
print(sorted(cars))

Avoid Index Errors

Check for list index out of range
Calling values where they don't exist

Clone this wiki locally