Python · Syntax · Beginner

for loop, list, tuple

15 tasks

Python for loop practice on lists and tuples: iterating through collections, filtering values, counting, finding minimums and maximums, working with strings, dates, and nested data.

The for loop and iterables

#
The for loop visits every item in an iterable — a list, tuple, string, or any sequence — one at a time. You never manage a counter manually: Python handles the stepping. ```python numbers = [3, 7, 1, 9, 4] for n in numbers: print(n) ``` Each iteration, n is bound to the next item in the list. When the list runs out, the loop ends. The same syntax works on tuples and strings — strings iterate character by character. The difference from while is intent. Use for when you know what you are iterating over. Use while when the number of iterations depends on a condition you are computing at runtime. enumerate gives you both the index and the value when you need them together: ```python days = ("Monday", "Tuesday", "Wednesday") for i, day in enumerate(days, start=1): print(f"Day {i}: {day}") ``` Without enumerate you would need a separate counter variable — enumerate removes that boilerplate.

Building collections while iterating

#
Many for-loop tasks follow the same shape: start with an empty list, loop over the source, decide whether to include each item, and append the keepers. ```python numbers = [2, 5, 0, 8, 11, 14, 17, 0] result = [] for n in numbers: if n % 2 == 0 and n != 0: result.append(n) print(result) ``` Appending to a list inside a loop is the standard filtering pattern. Append is O(1) — it does not copy the list each time. Accumulating a total works the same way, using a number instead of a list: ```python numbers = [5, 10, 15, 20] total = 0 for n in numbers: total += n print(total) ``` Tracking the current maximum — start with the first element as the initial guess, then update whenever you find something bigger: ```python numbers = [8, 3, 15, 6, 2] max_num = numbers[0] for n in numbers: if n > max_num: max_num = n print(max_num) ``` Starting with numbers[0] instead of 0 is important. If all numbers are negative, starting at 0 would give the wrong answer.

Key patterns from the exercises

#
Building a string by joining list elements — instead of appending to a string inside the loop (which creates a new string each time), collect items and join at the end: ```python numbers = [3, 7, 1, 9, 4] result = "-".join(str(n) for n in numbers) print(result) # 3-7-1-9-4 ``` str(n) converts each integer to a string before joining. join requires all elements to already be strings. Building a list of tuples — pair each item with computed data: ```python words = ["Python", "is", "cool"] result = [] for word in words: result.append((word, len(word))) print(result) # [('Python', 6), ('is', 2), ('cool', 4)] ``` Filtering by a property of a string: ```python words = ["python", "java", "go", "javascript", "c"] count = 0 for word in words: if len(word) > 5: count += 1 print(count) ``` Parsing structured data — split on a separator, then compare parts. The date filter exercise follows this pattern: compare the year-month-day parts of a date string against a threshold.

For loop, lists, and tuples quick reference

#
**for loop syntax** ```python for item in iterable: # list, tuple, string, range # body # with index — use enumerate for i, item in enumerate(items): # i starts at 0 for i, item in enumerate(items, start=1): # i starts at 1 # index-based — use range for i in range(5): # 0, 1, 2, 3, 4 for i in range(1, 6): # 1, 2, 3, 4, 5 for i in range(0, 10, 2): # 0, 2, 4, 6, 8 (step=2) ``` **Tuple quick reference** ```python point = (3, 7) # create with parentheses point[0] # access by index — same as list x, y = point # unpack into variables len(point) # 2 # tuples are immutable — point[0] = 5 raises TypeError ``` **Common for-loop patterns** | Pattern | Template | |---|---| | Filter into new list | `result = []; for x in xs: if cond: result.append(x)` | | Sum / accumulate | `total = 0; for x in xs: total += x` | | Count matches | `count = 0; for x in xs: if cond: count += 1` | | Find max / min | `m = xs[0]; for x in xs: if x > m: m = x` | | Build string | `result = ''.join(str(x) for x in xs)` | | List of tuples | `result.append((x, computed))` | **Useful built-ins that replace manual loops** ```python sum([1, 2, 3]) # 6 max([3, 1, 4]) # 4 min([3, 1, 4]) # 1 len([1, 2, 3]) # 3 sorted([3, 1, 2]) # [1, 2, 3] '-'.join(['a', 'b']) # 'a-b' ```
01

Numbers separated by hyphens.

#

A list of numbers is given. Display each number from the list in the same line in the terminal separated by hyphens. 3-7-1-9-4

numbers = [3, 7, 1, 9, 4]

Solution
numbers = [3, 7, 1, 9, 4]

result = ""
for n in numbers:
    result += str(n) + "-"

result = result[:-1]
print(result)

# or
numbers = [3, 7, 1, 9, 4]

for n in numbers[:-1]:
    print(n, end="-")
print(numbers[-1])

# or the shortest version using join
numbers = [3, 7, 1, 9, 4]

result = "-".join(str(n) for n in numbers)
print(result)
02

Even numbers without zeros.

#

A list of numbers is given. Add only even numbers to a new list, skip zeros.

numbers = [2, 5, 0, 8, 11, 14, 17, 0]
new = []

Solution
numbers = [2, 5, 0, 8, 11, 14, 17, 0]
new = []

for n in numbers:
    if n != 0 and n % 2 == 0:
        new.append(n)

print(new)

# or you can do this: first check for zero, and then for evenness
numbers = [2, 5, 0, 8, 11, 14, 17, 0]
new = []

for n in numbers:
    if n == 0:
        continue
    if n % 2 == 0:
        new.append(n)

print(new)
03

Sum of list elements.

#

A list of numbers is given. Find the sum of all elements in the list.

numbers = [5, 10, 15, 20]

total = 0
Solution
numbers = [5, 10, 15, 20]

total = 0
for n in numbers:
    total += n

print("Sum:", total)

# or
numbers = [5, 10, 15, 20]

total = sum(numbers)

print("Sum:", total)
04

Non-empty strings.

#

A list of strings is given. Add strings to a new list if they are not empty.

words = ["0000-0000-0000-0000", "", "1111-1111-1111-1111", "2222-2222-2222-2222", ""]
new_words = []

Solution
words = ["0000-0000-0000-0000", "", "1111-1111-1111-1111", "2222-2222-2222-2222", ""]
new_words = []

for w in words:
    if w != "":
        new_words.append(w)

print(new_words)

# or

words = ["0000-0000-0000-0000", "", "1111-1111-1111-1111", "2222-2222-2222-2222", ""]
new_words = []

for w in words:
    if w:
        new_words.append(w)

print(new_words)
05

Squares of numbers greater than 10.

#

A list of numbers is given. Create a new list that will contain squared only numbers greater than 10.

numbers = [3, 12, 5, 18, 7, 25]

result = []
Solution
numbers = [3, 12, 5, 18, 7, 25]

result = []
for n in numbers:
    if n > 10:
        result.append(n ** 2)

print(result)

# or you can do this: first save the square into a variable
numbers = [3, 12, 5, 18, 7, 25]

result = []
for n in numbers:
    if n > 10:
        square = n ** 2
        result.append(square)

print(result)
06

Days of the week with numbers.

#

A tuple with the names of weekdays is given. Display each day in the format: "Day X: <name>" .

days = ("Monday", "Tuesday", "Wednesday", "Thursday", "Friday")

Solution
days = ("Monday", "Tuesday", "Wednesday", "Thursday", "Friday")

day_num = 1
for day in days:
    print(f"Day {day_num}: {day}")
    day_num += 1

# or you can do this with enumerate
days = ("Monday", "Tuesday", "Wednesday", "Thursday", "Friday")

for number, day in enumerate(days, 1):
    print(f"Day {number}: {day}")
07

Maximum using a loop.

#

A list of numbers is given. Find the maximum number in the list using a for loop.

numbers = [8, 3, 15, 6, 2]

max_num = numbers[0]
Solution
numbers = [8, 3, 15, 6, 2]

max_num = numbers[0]
for n in numbers:
    if n > max_num:
        max_num = n

print("Maximum:", max_num)

# in general, there is a built-in max function for this:
numbers = [8, 3, 15, 6, 2]

max_num = max(numbers)
print("Maximum:", max_num)
08

Strings longer than 5 characters.

#

A list of strings is given. Count how many strings are longer than 5 characters.

words = ["python", "java", "go", "javascript", "c"]

count = 0
Solution
words = ["python", "java", "go", "javascript", "c"]

count = 0
for w in words:
    if len(w) > 5:
        count += 1

print("Number of strings:", count)

# or you can do this: save the length in a variable
words = ["python", "java", "go", "javascript", "c"]

count = 0
for w in words:
    length = len(w)
    if length > 5:
        count += 1

print("Number of strings:", count)
09

Positive numbers from a tuple.

#

A tuple of numbers is given. Display only the numbers that are greater than 0.

numbers = (-3, 5, -1, 7, 0, -2)

Solution
numbers = (-3, 5, -1, 7, 0, -2)

for n in numbers:
    if n > 0:
        print(n)

# or you can do this: collect positive numbers into a new list
numbers = (-3, 5, -1, 7, 0, -2)
positive = []

for n in numbers:
    if n > 0:
        positive.append(n)

print(positive)
10

String separated by commas.

#

A list of strings is given. Create a string that will consist of all list elements, separated by a comma and a space.

words = ["Python", "is", "cool"]

result = ""
Solution
words = ["Python", "is", "cool"]

result = ""
for w in words:
    result += w + ", "

result = result[:-2]
print(result)

# or shorter using join
words = ["Python", "is", "cool"]

result = ", ".join(words)
print(result)
11

Words and their lengths.

#

Would you be so kind 🧐 as to create from this list of strings a new list in which the elements will be tuples. Each tuple should contain two elements: the string and its length, for example: words = ["Python", "is", "cool"] new = [("Python", 6), ("is", 2), ("cool", 4)]

words = ["Python", "это", "круто"]
new = []

Solution
words = ["Python", "is", "cool"]
new = []

for word in words:
    t = (word, len(word))
    new.append(t)

print(new)


# Or the same thing shorter:
words = ["Python", "is", "cool"]
new = []

for word in words:
    new.append((word, len(word)))

print(new)
12

String characters in lowercase.

#

Hmm... We urgently need to make from this string "This", a list that will consist of the characters of this string in lowercase!!! (small letters)

word = "This"

Solution
word = "This"

arr = list(word.lower())  # yes, that's all.

print(arr)

# or through a loop, to clearly see the addition of each character
word = "This"
arr = []

for char in word:
    arr.append(char.lower())

print(arr)
13

Card number with hyphens.

#

Again urgently! Some smart guy saved the bank card number as a list of 4-digit card parts: card = ["1111", "2222", "3333", "4444"] Turn this into a string in the following format: norm_card = "1111-2222-3333-4444"

card = ["1111", "2222", "3333", "4444"]

Solution
card = ["1111", "2222", "3333", "4444"]

# This is urgent:
norm_card = "-".join(card)
print(norm_card)


# This is not urgent:
norm_card = ""

for part in card:
    norm_card += part + "-"
else:
    norm_card = norm_card[:-1]
print(norm_card)
14

Minimum, maximum, and average.

#

We continue the urgent quest! Quickly find: - the minimum value in the list; - the maximum value in the list; - the sum of all values in the list; - the arithmetic mean of the values in the list. And then, if you want, not so quickly.

arr = [10, 100, 500, 11, 18, 99, -3, 101]

Solution
arr = [10, 100, 500, 11, 18, 99, -3, 101]

# quickly:
mn = min(arr)
mx = max(arr)
sm = sum(arr)
am = sum(arr)/len(arr)
print(mn, mx, sm, am)


# not quickly:
mn = arr[0]
mx = arr[0]
sm = 0

for num in arr:
    sm += num
    if num < mn:
        mn = num
    if num > mx:
        mx = num

am = sm/len(arr)

print(mn, mx, sm, am)
15

Filter dates after 2027.09.01.

#

Finally, 5 minutes before the end of the workday, we need to do this: There is a list with dates in the strict format yyyy.mm.dd: dates = ["2027.09.25", "2027.10.14", "2027.03.01", "2027.12.29", "2027.09.11", "2027.05.06"] We need a new list that will contain only dates after 2027.09.01. Hint: try comparing strings with < - > , sometimes it is useful😉.

dates = ["2027.09.25", "2027.10.14", "2027.03.01", "2027.12.29", "2027.09.11", "2027.05.06"]
new = []
Solution
dates = ["2027.09.25", "2027.10.14", "2027.03.01", "2027.12.29", "2027.09.11", "2027.05.06"]

new = []

for date in dates:
    if date >= "2027.09.01":
        new.append(date)

print(new)

It is important to understand here that strings are compared lexicographically - that is, not as date numbers, but simply as each individual character. And this is one of the rare cases where comparing strings with < > can be used, besides, of course, alphabetical sorting.
IMPORTANT: the date format must be exactly like this, otherwise if you write dd.mm.yyyy it will no longer work the way we would like.

# or you can do this: save the boundary in a separate variable
dates = ["2027.09.25", "2027.10.14", "2027.03.01", "2027.12.29", "2027.09.11", "2027.05.06"]
border = "2027.09.01"
new_dates = []

for date in dates:
    if date > border:
        new_dates.append(date)

print(new_dates)