Python · Syntax · Beginner
for loop, list, tuple
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.
Quick topic start and explanations before exercises (exercises below):
Building collections while iterating
#Key patterns from the exercises
#For loop, lists, and tuples quick reference
#Exercises:
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)
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)
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)
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)
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)
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}")
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)
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)
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)
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)
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)
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)
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)
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)
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)