items = ["apple", "banana", "cherry", "date", "elderberry", "fig"]
for item in items:
print(f"item: {item}!")
item: apple!
item: banana!
item: cherry!
item: date!
item: elderberry!
item: fig!
Loops
for
loop
while
loop
enumerate
for this.for
loops, not while
loops.from datetime import datetime, timedelta
ds = [
{"name": "John", "age": 25},
{"name": "Jane", "age": 30},
{"name": "Jack", "age": 35},
]
names = [d["name"] for d in ds]
date = datetime.now()
dates = []
while date < datetime.now() + timedelta(days=10):
dates.append(date)
date += timedelta(days=1)
print(names)
formatted_dates = [datetime.strftime(date, "%Y-%m-%d") for date in dates]
print("dates", formatted_dates)
['John', 'Jane', 'Jack']
dates ['2024-09-18', '2024-09-19', '2024-09-20', '2024-09-21', '2024-09-22', '2024-09-23', '2024-09-24', '2024-09-25', '2024-09-26', '2024-09-27']
items = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
objs = [
{"name": "John", "cities": ["New York", "Los Angeles", "Chicago"]},
{"name": "Jane", "cities": ["San Francisco", "Seattle", "Portland"]},
]
for i1, row in enumerate(items):
print(f"Row {i1}")
for i2, item in enumerate(row):
print(f"Item {i2}: {item}")
Row 0
Item 0: 1
Item 1: 2
Item 2: 3
Row 1
Item 0: 4
Item 1: 5
Item 2: 6
Row 2
Item 0: 7
Item 1: 8
Item 2: 9
break
: stop the loop.continue
: skip the rest of the loop and go to the next iteration.else
: run when the loop is done without break
.items = ["apple", "banana", "cherry", "date", "elderberry", "date", "fig"]
new = []
for item in items:
if item == "date":
new.insert(0, item)
new.append(item)
else:
print("Done", new)
Done ['date', 'date', 'apple', 'banana', 'cherry', 'date', 'elderberry', 'date', 'fig']