Code / Python for Beginners / Unit 4: Lists and dictionaries

Lists लिस्ट

Lesson 10 of 14 · about 16 minutes · Many values in one variable: append, len, sum, max, slicing, in.

⚡ 0 XP

Step 1 of 2

A list of scores

Masala chaiBun maskaPoha

A list keeps many values in order, inside square brackets: scores = [45, 12, 78].

  • scores[0] is the first item (counting starts at 0!), scores[-1] is the last
  • scores.append(33) adds 33 at the end
  • len(scores) is how many items
  • sum(scores), max(scores), min(scores) do the maths for you

You can loop over a list directly: for s in scores:.

Example
scores = [45, 12, 78]
scores.append(33)
print(scores)
print("First:", scores[0], "Last:", scores[-1])
print("Matches:", len(scores), "Total:", sum(scores))

🎯 Challenge: Season scores +20 XP

A batter’s scores (sample data) are in scores. She scored 61 in the latest match: append it. Then print, using len, sum and max:

  • Matches: 5
  • Total: 229
  • Highest: 78
  • Average: 45.8 (total ÷ matches)

Try twice to unlock the solution (0/2)

main.pyCtrl ⏎
Output

What your program prints appears here.

Checklist

Press Run to check your code.

  • 61 is appended
  • Shows matches, total and highest
  • Shows the average
  • Uses len, sum and max
Lesson notes (text version)

1. A list of scores

A list keeps many values in order, inside square brackets: scores = [45, 12, 78].

  • scores[0] is the first item (counting starts at 0!), scores[-1] is the last
  • scores.append(33) adds 33 at the end
  • len(scores) is how many items
  • sum(scores), max(scores), min(scores) do the maths for you

You can loop over a list directly: for s in scores:.

                scores = [45, 12, 78]
scores.append(33)
print(scores)
print("First:", scores[0], "Last:", scores[-1])
print("Matches:", len(scores), "Total:", sum(scores))
              

Challenge: Season scores

A batter’s scores (sample data) are in scores. She scored 61 in the latest match: append it. Then print, using len, sum and max:

  • Matches: 5
  • Total: 229
  • Highest: 78
  • Average: 45.8 (total ÷ matches)

2. Slices and in

A slice takes a piece of a list: cart[1:3] gives the items at positions 1 and 2 (the end is not included, just like range).

  • cart[:3] is the first three items
  • cart[2:] is everything from position 2 to the end

in checks whether something is inside a list: "dal" in cart is True or False. Perfect for an if.

                cart = ["atta", "dal", "rice", "ghee"]
print(cart[:2])
print(cart[-1])
print("dal" in cart, "salt" in cart)
              

Challenge: Kirana shopping list

Print the first three items of cart with a slice, like First three: ['atta', 'dal', 'rice']. Then read an item. If it is already in the cart, print dal is already in the cart. If not, append it and print Added salt. Items now: 6.

Search by task, format or tool name.