LEARN COMPLETE PYTHON IN 24 HOURS
7. Lists – Most Important Data Structure
A list is an ordered, changeable (mutable), and indexed collection of items. You can store anything in a list: numbers, strings, booleans, other lists, etc.
7.1 Creating Lists
Ways to create a list:
Empty list
Python
my_list = [] empty = list() # same thing
With values
Python
fruits = ["apple", "banana", "mango", "orange"] numbers = [10, 20, 30, 40, 50] mixed = [1, "hello", True, 3.14, [5, 6]] # mixed types allowed!
From other data (using list())
Python
chars = list("Python") # ['P', 'y', 't', 'h', 'o', 'n'] range_list = list(range(1, 6)) # [1, 2, 3, 4, 5]
Length of list
Python
print(len(fruits)) # 4
Tip: Lists are mutable — you can change them after creation (unlike strings or tuples).
7.2 Accessing, Slicing & Negative Indexing
Lists are zero-indexed (first item = index 0).
Access single item
Python
fruits = ["apple", "banana", "mango", "orange"] print(fruits[0]) # apple print(fruits[2]) # mango print(fruits[-1]) # orange (last item) print(fruits[-2]) # mango (second last)
Slicing (get a part of the list)
Python
print(fruits[1:3]) # ['banana', 'mango'] (start inclusive, end exclusive) print(fruits[:3]) # ['apple', 'banana', 'mango'] (from start) print(fruits[2:]) # ['mango', 'orange'] (to end) print(fruits[::2]) # ['apple', 'mango'] (every 2nd item) print(fruits[::-1]) # ['orange', 'mango', 'banana', 'apple'] (reverse list)
Negative slicing example
Python
print(fruits[-3:-1]) # ['banana', 'mango']
Tip: Slicing creates a new list — original list remains unchanged.
7.3 List Methods (append, extend, insert, remove, pop, clear, sort, reverse, etc.)
Lists have many built-in methods — very powerful!
MethodDescriptionExampleResult after operationappend()Add one item at the endfruits.append("grapes")['apple', ..., 'grapes']extend()Add multiple items (from another list)fruits.extend(["kiwi", "pineapple"])Adds both itemsinsert()Insert at specific positionfruits.insert(1, "cherry")Insert at index 1remove()Remove first occurrence of valuefruits.remove("banana")Removes "banana"pop()Remove & return item (default: last)fruits.pop(2)Removes & returns item at index 2clear()Remove all itemsfruits.clear()[]sort()Sort list in place (ascending)numbers.sort()Sorted numbersreverse()Reverse the list in placefruits.reverse()Reversed orderindex()Find first index of valuefruits.index("mango")Returns index (or error if not found)count()Count occurrencesfruits.count("apple")Number of times "apple" appears
Practical Examples:
Python
# Start with this numbers = [30, 10, 50, 20] numbers.append(60) # [30, 10, 50, 20, 60] numbers.extend([70, 80]) # [30, 10, 50, 20, 60, 70, 80] numbers.insert(1, 15) # [30, 15, 10, 50, 20, 60, 70, 80] numbers.remove(50) # [30, 15, 10, 20, 60, 70, 80] last = numbers.pop() # removes 80, last = 80 print(last) # 80 numbers.sort() # [10, 15, 20, 30, 60, 70] numbers.reverse() # [70, 60, 30, 20, 15, 10] print(numbers.count(20)) # 1 print(numbers.index(30)) # 2 (after sorting & reversing)
Tip: sort() changes the original list. To get a sorted copy without changing original:
Python
sorted_numbers = sorted(numbers) # new sorted list
7.4 List Comprehension (Super Powerful & Short)
List comprehension is a concise way to create lists — very Pythonic and fast!
Basic Syntax:
Python
new_list = [expression for item in iterable if condition]
Examples:
Simple
Python
squares = [x**2 for x in range(1, 6)] print(squares) # [1, 4, 9, 16, 25]
With condition
Python
evens = [x for x in range(1, 11) if x % 2 == 0] print(evens) # [2, 4, 6, 8, 10]
With strings
Python
names = ["anshuman", "rahul", "priya"] upper = [name.upper() for name in names] print(upper) # ['ANSHUMAN', 'RAHUL', 'PRIYA']
Nested comprehension (simple)
Python
pairs = [(x, y) for x in [1,2] for y in ['a','b']] print(pairs) # [(1, 'a'), (1, 'b'), (2, 'a'), (2, 'b')]
Old way vs Comprehension
Python
# Old way (longer) result = [] for num in range(10): if num % 2 == 0: result.append(num 2) # Comprehension (short & clean) result = [num 2 for num in range(10) if num % 2 == 0] print(result) # [0, 4, 8, 12, 16]
Tip: Use comprehensions for readability and speed — but don't make them too complex.
7.5 Looping through Lists
Three common ways to loop through lists:
Direct iteration (recommended most times)
Python
fruits = ["apple", "banana", "mango"] for fruit in fruits: print("I love", fruit)
Using range() + index
Python
for i in range(len(fruits)): print(f"Index {i}: {fruits[i]}")
Using enumerate() – Best for index + value
Python
for index, fruit in enumerate(fruits, start=1): print(f"{index}. {fruit}")
Output:
text
1. apple 2. banana 3. mango
Mini Project – To-Do List Manager (using lists)
Python
todo = [] while True: print("\n1. Add task 2. View tasks 3. Remove task 4. Exit") choice = input("Choose: ") if choice == "1": task = input("Enter task: ") todo.append(task) print("Task added!") elif choice == "2": if todo: print("Your To-Do List:") for i, task in enumerate(todo, 1): print(f"{i}. {task}") else: print("No tasks yet!") elif choice == "3": if todo: num = int(input("Task number to remove: ")) if 1 <= num <= len(todo): removed = todo.pop(num - 1) print(f"Removed: {removed}") else: print("Invalid number!") else: print("No tasks!") elif choice == "4": print("Goodbye!") break
This completes the full Lists section — now you know one of Python's most important tools!
Email-ibm.anshuman@gmail.com
© 2026 CodeForge AI | Privacy Policy |Terms of Service | Contact | Disclaimer | 1000 university college list|book library australia 2026
All my books are exclusively available on Amazon. The free notes/materials on globalcodemaster.com do NOT match even 1% with any of my PUBLISHED BOoks. Similar topics ≠ same content. Books have full details, exercises, chapters & structure — website notes do not.No book content is shared here. We fully comply with Amazon policies.