Keyboard Shortcuts N Next post
P Previous post
S Save / unsave
R Read aloud
T Toggle theme
/ Focus search
Esc Close panels
🔥
Ready to read...
DATA STRUCTURES Module 3 - Data Structures Python Python Basics Python Programming: From Zero to Real-World Applications

List Methods - append, sort, reverse, and More

Reviewed & accurate
AI Summary

What You Will Learn

Beginner

  • All list methods
  • sort vs sorted
  • In-place vs new list methods

List Methods Reference

MethodWhat it doesModifies original?
append(x)Add x to endYes
extend(iter)Add all items from iterableYes
insert(i, x)Insert x at index iYes
remove(x)Remove first occurrence of xYes
pop(i)Remove and return item at i (default: last)Yes
clear()Remove all itemsYes
index(x)Find index of first xNo
count(x)Count occurrences of xNo
sort()Sort in placeYes
reverse()Reverse in placeYes
copy()Return a shallow copyNo

sort() vs sorted()

Common confusion
list.sort() sorts IN PLACE and returns None. sorted(list) returns a NEW sorted list without modifying the original.
Terminalpython
numbers = [3, 1, 4, 1, 5, 9, 2, 6]

# sort() - modifies original
numbers.sort()
print(numbers)   # [1, 1, 2, 3, 4, 5, 6, 9]

# sorted() - returns new list
original = [3, 1, 4, 1, 5]
sorted_list = sorted(original)
print(original)      # [3, 1, 4, 1, 5] (unchanged)
print(sorted_list)   # [1, 1, 3, 4, 5]

# Sort descending
numbers.sort(reverse=True)
print(numbers)   # [9, 6, 5, 4, 3, 2, 1, 1]

Practical Exercise

Create [5, 2, 8, 1, 9, 3]
Sort with .sort() - print result
Create a new sorted copy with sorted()
Sort in reverse: .sort(reverse=True)
Count occurrences: [1,1,1,2,2].count(1)

Key Takeaways

  • 11 list methods: append, extend, insert, remove, pop, clear, index, count, sort, reverse, copy.
  • sort() modifies in place. sorted() returns new list.
  • append() adds one item. extend() adds multiple.
  • count(x) counts occurrences. index(x) finds position.
  • copy() creates a shallow copy.
Previously: Lesson 16 covered list basics.
Today: You learned: Every list method explained with examples.
Next: Lesson 18 covers tuples.
Test Your Knowledge
How did you find this?

Comments

Join the discussion! Sign in with your Google or Blogger account, or comment as Anonymous - no account needed. For quick questions, also reach me on Telegram @cytestch.

Comments