xSKILLby Infirals
Register

Python for Beginners

0 of 24 notes read 0%

Reading progress is saved to your INFIRALS account. Sign in to keep this note marked as read.

Lists

Basics8 min readLesson 5 of 8

A list is an ordered collection of values, written in square brackets with commas between items. The order matters because each item has a position. Lists can grow and shrink, so they suit a row of names or a set of scores. A list may hold values of different types, though a list of related values is easier to work with.

python
fruits = ['mango', 'pear', 'guava']
print(fruits[0])
print(fruits[-1])
print(len(fruits))

Output

mango
guava
3

5.1 Indexing and slicing

Indexes start at 0, so the first item is items[0]. A slice copies part of the list: items[1:3] contains positions 1 and 2, and stops before 3. Slicing returns a new list, while indexing returns the item stored at that position.

5.2 Changing the list in place

  • append() adds an item at the end.
  • insert() adds an item at a chosen position.
  • pop() removes an item and returns it.
python
tasks = ['read', 'write']
tasks.append('rest')
tasks[0] = 'review'
print(tasks)

Output

['review', 'write', 'rest']

5.3 Common mistake

tasks = tasks.append('rest') looks like it updates the list, but it sets tasks to None. append() adds the item and returns None, so the assignment throws away the list name. Call append() on its own line, then continue using the same list name.

python
scores = [72, 85, 91, 64]
print(scores[1:3])
print(sum(scores))
print(max(scores))

Output

[85, 91]
312
91

5.4 Practice

  1. Make a list of four tasks and add a fifth with append().
  2. Replace the second task, then remove the last one with pop().
  3. Print the final list and its length after each change, then try reading index 10 and read the error message.

Interview questions

3 questions from this note. Open one to see the answer; no account needed.

  • 01What index holds the first item of a list?

    Index `0`. Negative indexes count from the end, so `items[-1]` is the last item.

  • 02What does `append()` return?

    It returns `None` after adding the item to the list. The changed list is available through the original list name.

  • 03How do you copy the first three items of a list?

    Use a slice such as `items[:3]`, which returns a new list with the items at positions `0`, `1`, and `2`.

Quiz

Lists check

Two questions on adding, sorting and copying lists.

2 questions

Question 1 of 2

0/2 answered

Which method adds one item to the end of a list?

Answer all you can, then submit.