⚡0 XP🔥0

Lists

Lesson 15 of 33 ⏱ 6 min read ✎ 4 exercises ❓ 5-question quiz ▶ Runs Python

Store many values in one variable - create lists, index and slice them, add, remove, sort and search items, nested lists, and copying correctly.

What is a list?#

A list stores many values in a single variable, in order. It is the most used data structure in Python.

marks = [78, 85, 92, 66]
names = ["Asha", "Ravi", "Neha"]
mixed = [1, "two", 3.0, True, None]   # different types allowed
empty = []

Lists are:

  • Ordered - items keep their position.
  • Mutable - you can add, change and remove items.
  • Allow duplicates - the same value can appear many times.
  • Indexed - from 0, just like strings.
हिंदी में समझें

List को एक रजिस्टर या सूची की तरह समझें जिसमें कई चीज़ें क्रम से लिखी होती हैं। एक ही variable में आप 100 students के marks रख सकते हैं, बजाय 100 अलग variables बनाने के।

List की खास बातें: इसमें क्रम (order) बना रहता है, एक जैसी values दोबारा आ सकती हैं, और आप इसे बदल सकते हैं (mutable) - नई चीज़ जोड़ना, हटाना, बदलना सब संभव है।

Accessing items#

▶ Try it YourselfPython
Ctrl + Enter to run

Changing items#

▶ Try it YourselfPython
Ctrl + Enter to run

Adding items#

Method What it does Example
append(x) add one item at the end nums.append(5)
insert(i, x) add at position i nums.insert(0, 99)
extend(iterable) add each item of another list nums.extend([6, 7])
+ join two lists into a new list a + b
▶ Try it YourselfPython
Ctrl + Enter to run
Common Mistake

cart.append(["eraser", "scale"]) would add the list as a single item: [..., ['eraser', 'scale']]. Use extend to add the items one by one.

Removing items#

Method / statement What it does
remove(x) removes the first item equal to x (ValueError if not found)
pop() removes and returns the last item
pop(i) removes and returns the item at index i
del lst[i] deletes the item at index i (or a slice)
clear() removes everything
▶ Try it YourselfPython
Ctrl + Enter to run

Searching and counting#

▶ Try it YourselfPython
Ctrl + Enter to run

Sorting and reversing#

▶ Try it YourselfPython
Ctrl + Enter to run
हिंदी में समझें

list.sort() और sorted(list) में फर्क:

  • nums.sort() - इसी list को बदल देता है और कुछ return नहीं करता (None देता है)।
  • sorted(nums) - original list को नहीं छूता, एक नई sorted list देता है।

आम गलती: nums = nums.sort() लिखने पर nums में None आ जाता है!

Useful built-in functions#

▶ Try it YourselfPython
Ctrl + Enter to run

Looping through lists#

▶ Try it YourselfPython
Ctrl + Enter to run

Building a list in a loop#

▶ Try it YourselfPython
Ctrl + Enter to run

(Later you'll learn a one-line way to do this: [n * n for n in range(1, 6)].)

Nested lists (2D lists)#

A list can contain other lists - useful for tables and matrices:

▶ Try it YourselfPython
Ctrl + Enter to run

Copying a list correctly#

Assignment does not copy a list. Both names refer to the same list:

▶ Try it YourselfPython
Ctrl + Enter to run
Common Mistake

For nested lists, .copy() makes a shallow copy - the inner lists are still shared. Use import copy; copy.deepcopy(x) for a fully independent copy.

Unpacking#

point = [10, 20]
x, y = point

first, *rest = [1, 2, 3, 4]
print(first, rest)     # 1 [2, 3, 4]

List methods - quick reference#

Method Description
append(x) add item at end
extend(it) add all items from iterable
insert(i, x) insert at index
remove(x) remove first matching value
pop([i]) remove & return item
clear() remove all
index(x) position of first match
count(x) number of matches
sort() sort in place
reverse() reverse in place
copy() shallow copy

Summary#

  • Lists are ordered, mutable collections: [a, b, c].
  • Index and slice like strings; change items with lst[i] = value.
  • Add: append, insert, extend. Remove: remove, pop, del, clear.
  • sort() modifies; sorted() returns a new list.
  • b = a shares the same list - use a.copy() for a copy.

Practice Exercises

Write your code, then press Check. Your program is tested automatically.

1

Largest and smallest

Read numbers separated by spaces on one line. Print the largest number, the smallest number and the average (2 decimals), each on its own line.

Test input:
45 12 78 34 89 23
Expected output:
89
12
46.83
2

Remove duplicates, keep order

Given the list in the code, build a new list unique containing each value only once, in the order they first appear. Print unique.

Expected output:
['Indore', 'Bhopal', 'Ujjain', 'Dewas']
3

Second largest

Print the second largest distinct value in the list marks. (For the given list the answer is 88.)

Expected output:
88
4

Matrix sum

Print the sum of all numbers in the 2D list matrix, and then the sum of each row as a list.

Expected output:
45
[6, 15, 24]

Quick Quiz

Q1.

What is nums after nums = [1, 2, 3]; nums.append([4, 5])?

Q2.

Which method removes and returns the last item?

Q3.

What is the difference between nums.sort() and sorted(nums)?

Q4.

What is printed?

a = [1, 2]
b = a
b.append(3)
print(a)
Q5.

What is [10, 20, 30, 40][1:3]?