Lists (append, sort, pop, slice, in, enumerate) - Python Tutorial for Beginners #8
Video: Lists (append, sort, pop, slice, in, enumerate) - Python Tutorial for Beginners #8 by Taught by Celeste AI - AI Coding Coach
Watch full page →Lists (append, sort, pop, slice, in, enumerate) - Python Tutorial for Beginners #8
Python lists are versatile containers that hold ordered collections of items. This tutorial covers how to create lists, access elements using indexing and slicing, check membership with in, and manipulate lists with common methods like append, insert, remove, pop, and sort. Additionally, it demonstrates using enumerate to iterate with indexes, culminating in a simple grocery list manager project.
Code
# List Basics
colors = ["red", "green", "blue"]
print(colors[0]) # Access first element: red
print(colors[1:4]) # Slice from index 1 to 3 (4 excluded): ['green', 'blue']
print("red" in colors) # Check membership: True
# List Methods
fruits = ["apple", "banana"]
fruits.append("cherry") # Add 'cherry' at the end
fruits.insert(1, "mango") # Insert 'mango' at index 1
fruits.remove("banana") # Remove 'banana' by value
last = fruits.pop() # Remove and return last item ('cherry')
print(fruits) # ['apple', 'mango']
print("Popped item:", last)
nums = [3, 1, 4, 2]
nums.sort() # Sort list in ascending order
print(nums) # [1, 2, 3, 4]
# Grocery List Manager (mini project)
items = []
while True:
cmd = input("Command (add/show/quit): ").strip().lower()
if cmd == "add":
item = input("Item to add: ").strip()
items.append(item)
elif cmd == "show":
print("Grocery List:")
for i, item in enumerate(items, 1): # Enumerate starting at 1
print(f" {i}. {item}")
elif cmd == "quit":
break
else:
print("Unknown command. Use add, show, or quit.")
Key Points
- Lists are ordered, mutable collections created with square brackets and support indexing and slicing.
- The
inkeyword tests if an element exists in a list, returning a Boolean value. - Common list methods include
append()to add,insert()to place at a specific index,remove()to delete by value, andpop()to remove and return an element. - Sorting a list is done with
sort(), which modifies the list in place. enumerate()helps loop over a list while keeping track of element indexes, useful for displaying numbered lists.