Home Blogs All Courses
python c OA ( Online Assessment ) Amazon Web Services (AWS) leetcode dsa algorithms java Machine learning
Get Referral
Login Sign Up

Python Lists: Complete Guide with Methods, Slicing & List Comprehension


Imagine storing the marks of 60 students in 60 separate variables — impossible to manage! A list stores all of them in one place, in order, and lets you add, remove, sort and search them easily. Lists are the most used data structure in Python, and they appear in almost every coding interview. Let's master them.

Watch the video first, then use this blog as your notes. Every section has runnable examples, and at the end you will find a "Predict the Output" quiz, practice challenges, a self-check list, interview questions and a quick summary.

How to use this blog: Open the Python shell (type python in your terminal) or any online Python editor and type every example yourself. Change the values, break the code and see what happens — that is how concepts really stick.

1. What is a List?

A list is an ordered, mutable collection of items written inside square brackets [ ] and separated by commas.

marks = [85, 92, 78, 90]
fruits = ["apple", "mango", "banana"]
mixed = [1, "hello", 3.5, True, [1, 2]]   # any types, even another list
empty = []                               # or list()
print(type(marks))                       # <class 'list'>
PropertyMeaning
OrderedItems keep the order in which you added them
MutableYou can change, add and remove items after creation
Allows duplicates[1, 1, 2] is perfectly valid
HeterogeneousItems can be of different types
IndexedEach item has a position starting from 0

2. Indexing — Accessing Items

List:      [ 10,  20,  30,  40,  50 ]
Index:        0    1    2    3    4
Negative:    -5   -4   -3   -2   -1
nums = [10, 20, 30, 40, 50]
print(nums[0])       # 10   first item
print(nums[-1])      # 50   last item
print(nums[2])       # 30
print(len(nums))     # 5
# print(nums[5])     # IndexError: list index out of range

3. Slicing — Getting a Part of the List

Syntax: list[start : stop : step] — stop is not included.

l = [10, 20, 30, 40, 50]
print(l[1:4])        # [20, 30, 40]
print(l[:3])         # [10, 20, 30]
print(l[-2:])        # [40, 50]
print(l[::2])        # [10, 30, 50]   every 2nd item
print(l[::-1])       # [50, 40, 30, 20, 10]   reversed
print(l[:])          # a full copy

4. Changing Items

colors = ["red", "green", "blue"]
colors[1] = "yellow"
print(colors)        # ['red', 'yellow', 'blue']

colors[0:2] = ["black", "white"]
print(colors)        # ['black', 'white', 'blue']

5. Adding Items: append, insert, extend

l = [1, 2, 3]
l.append(4)          # add at the end
print(l)             # [1, 2, 3, 4]

l.insert(1, 15)      # insert 15 at index 1
print(l)             # [1, 15, 2, 3, 4]

l.extend([5, 6])     # add many items
print(l)             # [1, 15, 2, 3, 4, 5, 6]

append vs extend: [1, 2, 3].append([4, 5]) gives [1, 2, 3, [4, 5]] (one item: a list). [1, 2, 3].extend([4, 5]) gives [1, 2, 3, 4, 5].

6. Removing Items: remove, pop, del, clear

l = [10, 20, 30, 40, 50]
l.remove(30)         # remove by VALUE (first match)
print(l)             # [10, 20, 40, 50]

last = l.pop()       # remove and return the last item
print(last, l)       # 50 [10, 20, 40]

l.pop(0)             # remove by INDEX
print(l)             # [20, 40]

del l[0]             # delete by index
print(l)             # [40]

l.clear()            # remove everything
print(l)             # []
MethodRemoves byReturns item?Error if missing
remove(x)ValueNoValueError
pop(i)Index (default last)YesIndexError
del l[i]Index / sliceNoIndexError
clear()EverythingNo—

7. Searching, Counting and Sorting

nums = [5, 2, 9, 1, 5]
print(5 in nums)            # True
print(nums.index(9))        # 2
print(nums.count(5))        # 2
print(max(nums), min(nums), sum(nums))   # 9 1 22

print(sorted(nums))         # [1, 2, 5, 5, 9]   new list
print(nums)                 # [5, 2, 9, 1, 5]   original unchanged

nums.sort(reverse=True)     # sorts IN PLACE
print(nums)                 # [9, 5, 5, 2, 1]

nums.reverse()
print(nums)                 # [1, 2, 5, 5, 9]

Trap: x = nums.sort() makes x equal to None, because sort() changes the list in place and returns nothing. Use sorted() when you need a new list.

8. Looping Through a List

fruits = ["apple", "mango", "kiwi"]

for fruit in fruits:
    print(fruit)

for i, fruit in enumerate(fruits):
    print(i, fruit)          # 0 apple, 1 mango, 2 kiwi

names = ["Aman", "Riya"]
marks = [88, 95]
for name, mark in zip(names, marks):
    print(name, mark)        # Aman 88, Riya 95

9. List Comprehension — The Pythonic Way

Syntax: [expression for item in iterable if condition]

# Normal loop
squares = []
for x in range(1, 6):
    squares.append(x ** 2)

# Same thing with list comprehension
squares = [x ** 2 for x in range(1, 6)]
print(squares)                       # [1, 4, 9, 16, 25]

evens = [x for x in range(10) if x % 2 == 0]
print(evens)                         # [0, 2, 4, 6, 8]

words = ["python", "java", "c"]
print([w.upper() for w in words])    # ['PYTHON', 'JAVA', 'C']

10. Nested Lists (2D Lists / Matrix)

matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]
print(matrix[1][2])         # 6   (row 1, column 2)

for row in matrix:
    print(*row)
# 1 2 3
# 4 5 6
# 7 8 9

11. Copying Lists — A Classic Bug

a = [1, 2, 3]
b = a            # NOT a copy - both names point to the same list
b.append(4)
print(a)         # [1, 2, 3, 4]

c = a.copy()     # or a[:] or list(a) - a real (shallow) copy
c.append(99)
print(a)         # [1, 2, 3, 4]   unchanged

For nested lists, use copy.deepcopy() — a shallow copy still shares the inner lists.

12. Useful Operations

print([1, 2] + [3, 4])      # [1, 2, 3, 4]   concatenation
print([0] * 5)              # [0, 0, 0, 0, 0] repetition
print(list("abc"))          # ['a', 'b', 'c']
print(" ".join(["I", "love", "Python"]))   # I love Python
print("a,b,c".split(","))   # ['a', 'b', 'c']

All list methods

MethodDescription
append(x)Add x at the end
extend(iterable)Add all items of an iterable
insert(i, x)Insert x at index i
remove(x)Remove first occurrence of x
pop(i)Remove and return item at i (default last)
clear()Remove all items
index(x)Index of first x
count(x)Number of times x appears
sort()Sort in place
reverse()Reverse in place
copy()Shallow copy

13. Mini Project: Student Marks Analyzer

marks = [78, 92, 65, 88, 95, 54, 81]

print("Total students:", len(marks))
print("Highest:", max(marks))
print("Lowest:", min(marks))
print(f"Average: {sum(marks) / len(marks):.2f}")
print("Passed (>= 60):", [m for m in marks if m >= 60])
print("Top 3:", sorted(marks, reverse=True)[:3])
Total students: 7
Highest: 95
Lowest: 54
Average: 79.00
Passed (>= 60): [78, 92, 65, 88, 95, 81]
Top 3: [95, 92, 88]

Quiz: Predict the Output

Don't run the code yet! Write your answers in a notebook, then check the Answers section at the end of this blog.

Q1. What is the output?

l = [10, 20, 30, 40]
print(l[-1], l[1:3])

Q2. What is the output?

l = [1, 2, 3]
l.append([4, 5])
print(len(l))

Q3. What is the output?

x = [3, 1, 2]
print(x.sort())

Q4. What is the output?

print([1, 2] * 2)

Q5. What is the output?

a = [1, 2, 3]
b = a
b[0] = 100
print(a)

Q6. What is the output?

print([x * 2 for x in range(4) if x != 2])

Q7. What is the output?

l = [5, 6, 7]
print(l.pop(), l)

Practice Challenges

Solve these from easy to tricky:

  1. Create a list of 5 friends' names and print the first, last and middle names.
  2. Find the second largest number in [12, 45, 2, 41, 45, 30].
  3. Remove all duplicates from a list while keeping the original order.
  4. Using list comprehension, create a list of all numbers from 1 to 50 divisible by 7.
  5. Reverse a list without using reverse() or slicing.
  6. Given [[1, 2], [3, 4], [5, 6]], flatten it into [1, 2, 3, 4, 5, 6].

Solutions for challenges 2, 3, 4 and 6 are in the Answers section.

Self-Check: Can You Do This?

Tick off each skill once you are confident:

Frequently Asked Interview Questions

Q: Difference between append() and extend()?
append adds its argument as one item; extend adds every element of an iterable.

Q: Difference between sort() and sorted()?
sort() is a list method that changes the list and returns None. sorted() is a built-in that returns a new sorted list and works on any iterable.

Q: Difference between remove(), pop() and del?
remove deletes by value, pop deletes by index and returns the item, del deletes by index or slice (or the whole variable).

Q: What is the time complexity of common list operations?
Index access and append: O(1). insert/pop at the beginning, in search and remove: O(n). sort: O(n log n).

Q: What is the difference between a shallow copy and a deep copy?
A shallow copy creates a new outer list but shares the inner objects; a deep copy (copy.deepcopy) copies everything recursively.

Summary

  • A list is an ordered, mutable collection that allows duplicates: [1, 2, 3].
  • Index from 0 (or -1 from the end); slice with [start:stop:step].
  • Add: append, insert, extend. Remove: remove, pop, del, clear.
  • sort() changes the list; sorted() returns a new one.
  • List comprehensions are short and Pythonic.
  • b = a does not copy — use a.copy().

Quick Revision Cheat Sheet

ConceptSyntax / Key point
Createl = [1, 2, 3]
Accessl[0], l[-1]
Slicel[1:3], l[::-1]
Addl.append(x)
Removel.remove(x), l.pop()
Sortl.sort(), sorted(l)
Lengthlen(l)
Comprehension[x*2 for x in l]

Answers

Quiz answers

  1. 40 [20, 30]
  2. 4 – the inner list counts as one item.
  3. None – sort() works in place.
  4. [1, 2, 1, 2]
  5. [100, 2, 3] – same list object.
  6. [0, 2, 6]
  7. 7 [5, 6]

Challenge solutions

# Challenge 2
nums = [12, 45, 2, 41, 45, 30]
unique = sorted(set(nums), reverse=True)
print(unique[1])                       # 41

# Challenge 3
items = [3, 1, 3, 2, 1, 5]
result = []
for x in items:
    if x not in result:
        result.append(x)
print(result)                          # [3, 1, 2, 5]

# Challenge 4
print([n for n in range(1, 51) if n % 7 == 0])   # [7, 14, 21, 28, 35, 42, 49]

# Challenge 6
nested = [[1, 2], [3, 4], [5, 6]]
flat = [x for row in nested for x in row]
print(flat)                            # [1, 2, 3, 4, 5, 6]

Conclusion

Lists are your Swiss-army knife in Python. You can now create, access, modify, sort and transform them like a pro. Next, learn if / elif / else to make your programs take decisions.

If this blog helped you, watch the full video above, subscribe to the channel and share it with a friend who is learning Python. Happy coding!