# Python List Examples
# ── Creating lists ────────────────────────────────────────────────────────────
empty_list = []
numbers = [1, 2, 3, 4, 5]
mixed = [42, "hello", 3.14, True]
nested = [[1, 2], [3, 4], [5, 6]]
from_range = list(range(1, 6)) # [1, 2, 3, 4, 5]
# ── Indexing and slicing ──────────────────────────────────────────────────────
fruits = ["apple", "banana", "cherry", "date", "elderberry"]
print(fruits[0]) # apple
print(fruits[-1]) # elderberry
print(fruits[1:3]) # ['banana', 'cherry']
print(fruits[:3]) # ['apple', 'banana', 'cherry']
print(fruits[2:]) # ['cherry', 'date', 'elderberry']
print(fruits[::2]) # ['apple', 'cherry', 'elderberry']
print(fruits[::-1]) # ['elderberry', 'date', 'cherry', 'banana', 'apple']
# ── List methods ──────────────────────────────────────────────────────────────
colors = ["red", "green", "blue"]
colors.append("yellow") # colors → ['red', 'green', 'blue', 'yellow']
colors.insert(1, "orange") # colors → ['red', 'orange', 'green', 'blue', 'yellow']
colors.remove("green") # colors → ['red', 'orange', 'blue', 'yellow']
popped = colors.pop() # popped → 'yellow' | colors → ['red', 'orange', 'blue']
popped_at = colors.pop(1) # popped_at → 'orange' | colors → ['red', 'blue']
nums = [3, 1, 4, 1, 5, 9, 2, 6]
nums.sort() # nums → [1, 1, 2, 3, 4, 5, 6, 9]
nums.sort(reverse=True) # nums → [9, 6, 5, 4, 3, 2, 1, 1]
sorted_copy = sorted(nums) # sorted_copy → [1, 1, 2, 3, 4, 5, 6, 9] | nums unchanged
nums.reverse() # nums → [1, 1, 2, 3, 4, 5, 6, 9]
print(nums.count(1)) # 2
print(nums.index(5)) # 5
nums.extend([10, 11]) # nums → [1, 1, 2, 3, 4, 5, 6, 9, 10, 11]
nums.clear() # nums → []
# ── Iterating through lists ───────────────────────────────────────────────────
animals = ["cat", "dog", "fish"]
# Basic for loop
for animal in animals:
print(animal)
# cat
# dog
# fish
# With index using enumerate
for i, animal in enumerate(animals):
print(f"{i}: {animal}")
# 0: cat
# 1: dog
# 2: fish
# While loop
i = 0
while i < len(animals):
print(animals[i])
i += 1
# cat
# dog
# fish
# List comprehension (create a new list while iterating)
squares = [x ** 2 for x in range(1, 6)] # [1, 4, 9, 16, 25]
evens = [x for x in range(1, 11) if x % 2 == 0] # [2, 4, 6, 8, 10]
# Iterating over two lists in parallel
names = ["Alice", "Bob", "Charlie"]
scores = [95, 87, 92]
for name, score in zip(names, scores):
print(f"{name}: {score}")
# Alice: 95
# Bob: 87
# Charlie: 92
No comments:
Post a Comment
Please comment below to feedback or ask questions.