跳到主要内容

Lists

A list is a collection of items in a particular order. You can make a list that includes letters of the alphabet, digits, names, or any other items. Lists are one of Python's most useful features.

Creating and Accessing Lists

Basic List Creation

# Create a list
bicycles = ['trek', 'cannondale', 'redline', 'specialized']
print(bicycles)

Output:

['trek', 'cannondale', 'redline', 'specialized']

Accessing List Elements

Lists are ordered collections, so you can access any element by telling Python the position (index) of the item desired. List indices start at 0, not 1.

# Access elements by index
print(bicycles[0])
print(bicycles[0].title())

Output:

trek
Trek
# Access multiple elements
print(bicycles[0])
print(bicycles[1])
print(bicycles[2])
print(bicycles[3])
print(bicycles[-1]) # Last element

Output:

trek
cannondale
redline
specialized
specialized

Using List Values

# Using list index in a string
message = f"My first bicycle was a {bicycles[0].title()}."
print(message)

Output:

My first bicycle was a Trek.

Modifying Lists

Changing Elements

# Change an element
motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)

motorcycles[0] = 'ducati'
print(motorcycles)

Output:

['honda', 'yamaha', 'suzuki']
['ducati', 'yamaha', 'suzuki']

Adding Elements

Using append()

The append() method adds an element to the end of a list:

# Add to the end of the list
motorcycles.append('honda')
print(motorcycles)

Output:

['ducati', 'yamaha', 'suzuki', 'honda']

You can also build lists dynamically:

# Building a list dynamically
motorcycles = []
motorcycles.append('honda')
motorcycles.append('yamaha')
motorcycles.append('suzuki')
print(motorcycles)

Output:

['honda', 'yamaha', 'suzuki']

Using insert()

The insert() method adds an element at any position in the list:

# Insert at a specific position
motorcycles = ['honda', 'yamaha', 'suzuki']
motorcycles.insert(0, 'ducati')
print(motorcycles)

Output:

['ducati', 'honda', 'yamaha', 'suzuki']

Removing Elements

Using del

If you know the position of the item you want to remove, use the del statement:

# Delete by index
motorcycles = ['honda', 'yamaha', 'suzuki']
del motorcycles[0]
print(motorcycles)

Output:

['yamaha', 'suzuki']

Using pop()

The pop() method removes an element from a list and returns it (like a stack operation):

# Pop the last element
motorcycles = ['honda', 'yamaha', 'suzuki']
mine = motorcycles.pop()
print(mine)
print(motorcycles)

Output:

suzuki
['honda', 'yamaha']

You can also pop from any position:

# Pop from a specific position
motorcycles = ['honda', 'yamaha', 'suzuki']
first_owned = motorcycles.pop(1)
print(f"The first motorcycle I owned was a {first_owned.title()}.")

Output:

The first motorcycle I owned was a Yamaha.

Using remove()

The remove() method deletes an element by its value:

# Remove by value
motorcycles = ['honda', 'yamaha', 'suzuki', 'ducati']
motorcycles.remove('yamaha')
print(motorcycles)

Output:

['honda', 'suzuki', 'ducati']

You can also store the value in a variable first:

# Remove using a variable
motorcycles = ['honda', 'yamaha', 'suzuki', 'ducati']
too_expensive = 'yamaha'
motorcycles.remove(too_expensive)
print(motorcycles)
print(f'\nA {too_expensive.title()} is too expensive for me.')

Output:

['honda', 'suzuki', 'ducati']

A Yamaha is too expensive for me.
备注

The remove() method only deletes the first occurrence of the value. If the value appears multiple times, you'll need to use a loop.

Organizing Lists

Sorting Permanently with sort()

The sort() method permanently changes the order of the list:

# Sort alphabetically
cars = ["bmw", "audi", "toyota", "subaru"]
cars.sort()
print(cars)

Output:

['audi', 'bmw', 'subaru', 'toyota']
# Sort in reverse alphabetical order
cars = ["bmw", "audi", "toyota", "subaru"]
cars.sort(reverse=True)
print(cars)

Output:

['toyota', 'subaru', 'bmw', 'audi']

Sorting Temporarily with sorted()

The sorted() function displays a list in sorted order without affecting the original list:

# Temporary sorting
cars = ["bmw", "audi", "toyota", "subaru"]
print("Original:")
print(cars)
print("\nSorted:")
print(sorted(cars))
print("\nOriginal again:")
print(cars)

Output:

Original:
['bmw', 'audi', 'toyota', 'subaru']

Sorted:
['audi', 'bmw', 'subaru', 'toyota']

Original again:
['bmw', 'audi', 'toyota', 'subaru']
Sorting with Mixed Case

When sorting lists that contain both uppercase and lowercase letters, the results can be complex. Uppercase letters are sorted before lowercase letters.

# Mixed case sorting example
cars = ["bmw", "audi", "toyota", "subaru", "BMW"]
cars.sort()
print(cars)

Output:

['BMW', 'audi', 'bmw', 'subaru', 'toyota']

Reversing a List

The reverse() method reverses the original order of a list:

# Reverse the list order
cars = ["bmw", "audi", "toyota", "subaru"]
print(cars)
cars.reverse()
print(cars)

Output:

['bmw', 'audi', 'toyota', 'subaru']
['subaru', 'toyota', 'audi', 'bmw']

Finding List Length

Use the len() function to find the length of a list:

# Get list length
cars = ["bmw", "audi", "toyota", "subaru"]
print(len(cars))

Output:

4
# Empty list length
cars = []
print(len(cars))

Output:

0

Avoiding Index Errors

Python will give you an IndexError if you try to access an index that doesn't exist:

# This will cause an error
motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles[3]) # IndexError: list index out of range
Using Negative Indices

Remember that index[-1] always returns the last element of a list, which is useful for avoiding index errors when you don't know the length of the list.

motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles[-1]) # suzuki

Summary

In this chapter, you learned:

  • How to define a list and work with individual elements
  • How to add, remove, and modify elements
  • How to organize lists permanently and temporarily
  • How to avoid common index errors

Lists are fundamental to Python programming, and you'll use them frequently in your programs. The ability to work with collections of information is essential for handling real-world data effectively.