Walrus Operator Loop in Python

Level 5371 keystrokes

This uses the walrus operator (:=) to assign and test a value in a single expression within a loop.

Python code

# Import re for regular expressions
1import re
2
# Sample text with email addresses
3text = "Contact: email1@test.com, email2@example.org, invalid@"
# Regex pattern for valid email format
4pattern = r"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}"
5
# List to collect valid emails
6valid_emails = []
# Iterate through each word in text
7for word in text.split():
# Remove trailing comma
8 word = word.strip(",")
# Walrus operator assigns match AND checks if truthy
9 if (match := re.search(pattern, word)):
# Match found ("Contact:" and "invalid@" never match): add it to the list
10 valid_emails.append(match.group())
11
# Print count of valid emails
12print(f"Found {len(valid_emails)} emails:")
# Print each valid email
13for email in valid_emails:
# Format with bullet point
14 print(f" - {email}")

Output

Found 2 emails:
  - email1@test.com
  - email2@example.org
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this Python code and how often they appear.

  • -× 11
  • .× 10
  • "× 10
  • (× 9
  • )× 9
  • :× 6
  • _× 5
  • ,× 5
  • =× 5
  • [× 4

More Python examples at level 5

← Python typing practice