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 itemitems.append(x)— add at the enditems.remove(x)— remove by valuelen(items)— how many itemssorted(items)— a sorted copy
How.
Work with a list
- Create it with
[]. - Read items by index (from 0).
- Add with
append. - Remove with
remove. - Check the count with
len.
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.
Ravindra Bagale's Tip – मराठी
sorted(x) नवी sorted list देतो आणि जुनी ठेवतो. x.sort() list स्वतःच बदलतो आणि काहीच return करत नाही. Beginners अनेकदा x = x.sort() लिहितात आणि None मिळतं.
Ravindra Bagale's Tip – हिंदी
sorted(x) नई sorted list देता है और पुरानी रखता है. x.sort() list को ही बदलता है और कुछ return नहीं करता. Beginners अक्सर x = x.sort() लिखते हैं और None मिलता है.