Ravindra BagaleCourses & study guides मराठी Track your progress

Python Lists, Tuples, Dictionaries and Sets Explained with Examples

P4.1 Python Lists: Create, Access, Add and Remove Items

Why. A list keeps many values in order, like one column in Excel. You can add, remove and sort items.

What. A list is written with square brackets [] and commas. It can change after you create it.

  • items[0] — first item
  • items.append(x) — add at the end
  • items.remove(x) — remove by value
  • len(items) — how many items
  • sorted(items) — a sorted copy

How.

Work with a list

  1. Create it with [].
  2. Read items by index (from 0).
  3. Add with append.
  4. Remove with remove.
  5. Check the count with len.
1. Create: [120, 80]2. append(95) → [120, 80, 95]3. remove(80) → [120, 95]4. sorted() → [95, 120]
Life of a list (read from top to bottom)

Worked example A — Create and read a list.

Step 1 — What we do. Daily orders for a café in Manchester for 4 days.

Step 2 — Type and run this code.

orders = [120, 85, 140, 98]
print(orders)
print(orders[0])
print(orders[-1])
print(len(orders))

Step 3 — Output you should see.

[120, 85, 140, 98]
120
98
4

Step 4 — What it means. Index 0 is day 1, -1 the last day. len tells us there are 4 days.

Worked example B — Add and remove.

Step 1 — What we do. Day 5 sales come in, and a wrong entry of 85 must be removed.

Step 2 — Type and run this code.

orders = [120, 85, 140, 98]
orders.append(110)
orders.remove(85)
print(orders)

Step 3 — Output you should see.

[120, 140, 98, 110]

Step 4 — What it means. append adds 110 at the end. remove deletes the first 85 it finds.

Worked example C — Total, average, min, max.

Step 1 — What we do. Same orders. We get quick summary numbers.

Step 2 — Type and run this code.

orders = [120, 140, 98, 110]
print(sum(orders))
print(sum(orders) / len(orders))
print(min(orders), max(orders))

Step 3 — Output you should see.

468
117.0
98 140

Step 4 — What it means. These are the same summaries pandas gives with .sum(), .mean(), .min() and .max().

Worked example D — Slice and sort.

Step 1 — What we do. We want the first two days and the orders from highest to lowest.

Step 2 — Type and run this code.

orders = [120, 140, 98, 110]
print(orders[0:2])
print(sorted(orders, reverse=True))

Step 3 — Output you should see.

[120, 140]
[140, 120, 110, 98]

Step 4 — What it means. Slicing works exactly like strings. reverse=True sorts from big to small.

Ravindra Bagale's Tip

sorted(x) gives a new sorted list and keeps the old one. x.sort() changes the list itself and returns nothing. Beginners often write x = x.sort() and get None.