Python provides a variety of built-in data structures like lists, tuples, dictionaries, sets etc. that store data in different ways. Iterating through these data structures and applying conditional logic is an essential aspect of Python programming. This guide will walk through practical examples to help you master iterating and conditional programming in Python.
Table of Contents
Open Table of Contents
Overview of Data Structures in Python
Let’s first briefly introduce the main data structures in Python that we will be covering in this guide:
Lists
Lists are ordered sequences of elements enclosed in square brackets []
. Lists can contain elements of different data types like integers, strings etc. Elements can be accessed by index, with the first element at index 0. Lists are mutable, meaning the elements can be changed after creation.
# Create a list
languages = ['Python', 'R', 'Java']
# Access element at index 0
print(languages[0]) # 'Python'
# Change element at index 2
languages[2] = 'JavaScript'
print(languages) # ['Python', 'R', 'JavaScript']
Tuples
Tuples are similar to lists, but the elements are enclosed in parentheses ()
and are immutable, meaning they cannot be changed once created.
digits = (0, 1, 2, 3, 4)
# Access element at index 3
print(digits[3]) # 3
# Tuples cannot be modified
digits[2] = 5 # Throws error
Dictionaries
Dictionaries consist of key-value pairs enclosed in curly braces {}
. The keys are used to access the values. Dictionaries are unordered and mutable.
person = {'name': 'John', 'age': 20, 'jobs': ['Software Engineer', 'Writer']}
# Access value using key
print(person['name']) # 'John'
# Add new key-value pair
person['city'] = 'New York'
Sets
Sets are unordered collections of unique elements enclosed in curly braces {}
. They can perform fast membership testing and eliminate duplicates. Sets are mutable but cannot contain duplicate elements.
colors = {'red', 'blue', 'green'}
# Add new element
colors.add('violet')
# Sets do not allow duplicates
colors.add('blue') # No error, but duplicate not added
Now that we have a basic understanding of Python’s data structures, let’s go through examples of iterating through them and applying conditional logic.
Iterating Through Data Structures
We can loop over the elements in data structures to access each element sequentially. The two main ways to iterate in Python are for
loops and while
loops.
For Loops
For loops allow iterating over elements of a sequence like lists, tuples, strings etc. The basic syntax is:
for element in sequence:
# Do something with element
Let’s go through examples of for loops with different data structures:
Lists
languages = ['Python', 'R', 'Java']
for language in languages:
print(language)
# Output:
# Python
# R
# Java
We can also access the index within the for loop using enumerate()
:
for index, language in enumerate(languages):
print(f'{index}: {language}')
# Output:
# 0: Python
# 1: R
# 2: Java
Tuples
digits = (0, 1, 2, 3, 4)
for digit in digits:
print(digit)
# Output:
# 0
# 1
# 2
# 3
# 4
Dictionaries
For dictionaries, we can iterate through keys, values or key-value pairs:
person = {'name': 'John', 'age': 20, 'jobs': ['Software Engineer', 'Writer']}
# Iterate through keys
for key in person:
print(key)
# Iterate through values
for value in person.values():
print(value)
# Iterate through key-value pairs
for key, value in person.items():
print(f'{key}: {value}')
This prints:
name
age
jobs
John
20
['Software Engineer', 'Writer']
name: John
age: 20
jobs: ['Software Engineer', 'Writer']
Sets
Since sets are unordered, elements are accessed in arbitrary order.
colors = {'red', 'blue', 'green'}
for color in colors:
print(color)
# Output (in random order):
# green
# red
# blue
While Loops
While loops continue executing a block of code as long as the condition is true.
count = 0
while count < 5:
print(count)
count += 1
This prints numbers 0 to 4.
While loops are useful when the number of iterations is not known and depends on a condition.
Applying Conditionals
We can control the flow of iteration using conditional statements like if
, else
and elif
. Let’s look at some examples:
If Statements
numbers = [1, 2, 3, 4, 5]
for number in numbers:
if number % 2 == 0:
print(f'{number} is even')
else:
print(f'{number} is odd')
# Output:
# 1 is odd
# 2 is even
# 3 is odd
# 4 is even
# 5 is odd
This checks if each number is even or odd.
We can add an optional elif
(else if) to check multiple conditions:
grade = 'B'
if grade == 'A':
print('Excellent')
elif grade == 'B':
print('Good')
elif grade == 'C':
print('Fair')
else:
print('Poor')
# Output: Good
Nested Conditionals
We can have conditionals inside other conditionals to check complex logic.
person = {'name': 'John', 'age': 20, 'jobs': ['Software Engineer', 'Writer']}
if 'name' in person:
name = person['name']
if name == 'John':
print(f'{name} is a Software Engineer!')
else:
print(f'{name} is some other person.')
else:
print('Person has no name!')
This first checks if ‘name’ key exists in dictionary, then checks if name equals ‘John’ and prints appropriate message.
Conditional Expressions
We can use conditional expressions like x if C else y
to inline simple conditionals and make code more concise:
values = [1, 2, 3, 4]
print('Even' if x%2==0 else 'Odd' for x in values)
# Output:
# Odd
# Even
# Odd
# Even
This prints if each number is even or odd in one line without using an if-else block.
Practical Examples
Let’s now look at some practical real-world examples combining iteration and conditionals in Python.
Filtering a List
We can filter a list to contain only elements that satisfy a condition using a list comprehension:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = [x for x in numbers if x%2 == 0]
print(even_numbers)
# Output: [2, 4, 6, 8, 10]
This creates a new list even_numbers
containing only even numbers from the numbers
list.
Finding the Maximum Value
To find the maximum value in a collection, we can iterate through the elements and keep track of the largest value seen:
values = [10, 3, 8, 14, 9]
maximum = values[0]
for value in values:
if value > maximum:
maximum = value
print(maximum) # 14
Here we assume first element is maximum initially, then compare each subsequent element to update maximum if a larger value is found.
Counting Occurences
To count occurrences of items in a collection, we can utilize a dictionary to keep track of frequencies:
names = ['John', 'Mary', 'Lucy', 'Mary', 'John', 'Lucy']
name_counts = {}
for name in names:
if name in name_counts:
name_counts[name] += 1
else:
name_counts[name] = 1
print(name_counts)
# {'John': 2, 'Mary': 2, 'Lucy': 2}
This counts how many times each name appears in the list using the dictionary.
Dictionary Comprehensions
Comprehensions provide a concise way to transform or filter data structures. We can create a dictionary comprehension to invert keys and values of a dictionary:
person = {'name': 'John', 'age': 20, 'jobs': ['Software Engineer', 'Writer']}
inverted = {value : key for key, value in person.items()}
print(inverted)
# Output:
# {'John' : 'name', 20 : 'age', ['Software Engineer', 'Writer'] : 'jobs'}
This creates a new dictionary with values as keys and keys as values.
As we have seen, iterating over data structures while applying conditional logic is a common programming task. Mastering these core concepts provides a strong foundation for solving real-world problems using Python.
Summary
- Python has built-in data structures like lists, tuples, dictionaries and sets to organize data.
- Use for loops to iterate through elements of a data structure.
- While loops execute a block of code repeatedly as long as a condition is true.
- If, else and elif allow conditional code execution based on results of logical tests.
- Nested conditionals and conditional expressions can implement complex logic concisely.
- Iteration and conditionals are very useful together for filtering, counting occurrences, finding maximum/minimum, transforming data structures etc.