PedroGeoGISdev
  • Home
  • Linux OS
    • Linux: concepts
    • Linux: basic concepts
    • Linux: Bash
    • Linux: su and sudo
    • Linux: pipes
    • Linux: File System
    • Linux: Virtual Machines

    • Linux: distros
    • Linux Distros: Ubuntu
    • Linux Distros: Mint
    • Linux Distros: Debian
    • Linux Distros: openSuse
    • Linux Distros: Manjaro
    • Linux Distros: Red Hat Enterprise

    • Linux: laboratories
    • Linux Lab#LI01-1: Choose Linux
    • Linux Lab#LI01-2: Install at least three distributions
    • Linux Lab#LI01-3: Adjust user permissions
    • Linux Lab#LI02-1: Export env user with grep and pipe
    • Linux Lab#LI03-1: Manage users and groups
    • Linux Lab#LI03-2: Manage files
    • Linux Lab#LI03-3: Manage software
    • Linux Lab#LI03-4: Manage hardware
    • Linux Lab#LI04-1: Bash scripting, qtool
    • Linux Lab#LI04-2: Bash scripts as terminal tool
    • Linux Lab#LI04-3: Distribute the terminal app

    • Linux readings
    • Linux Resources
  • DevOps
    • What is DevOps
    • DevOps: Introduction
    • DevOps: Agile and Microservices
    • Infrastructure as code (IaC)
    • Immutable Infrastructure
    • Software Lifecycle

    • Documentation
    • How to document: Quarto and Obsidian

    • Network protocols
    • Network: Basics
    • Network: Client-server
    • Network Protocols
    • Network: DNS
    • Network: API Rest
    • Network: gRPC
    • Network: Websocket
    • Network: SMTP
    • Network: Ping
    • Network: UDP
    • Network: webhook
    • Network: SOAP
    • Network: graphQL

    • Version Control
    • Git
    • GitHub
    • Idea and GitHub 2023
    • Git and GitHub 2023 CLI

    • IDEs
    • IDE: Visual Code
    • IDE: IntellJIdea

    • DevOps tools
    • Amazon Web Services AWS
    • Docker
    • Jenkins pipelines
    • Kubernetes k8s
    • Digital Ocean
    • Nagios
    • Ansible

    • DevOps Laboratories
    • Lab 1: chat App
    • Lab 2: Spring Boot AWS AEB manually
    • Lab 3: Spring Boot and AWS S3 publisher
    • Lab 4: Spring Boot Docker/Jenkins
    • Lab 5: k8s on Digital Ocean
    • Lab 6: Spring Boot AWS codecommit

    • DevOps readings
    • DevOps Resources
  • MarkUp
    • MarkUp Languages
    • Introduction Markup
    • HTML Markup
    • Markdown Markup
    • Markdown and HTML working together, good idea?

    • Quarto Markdown
    • Quarto Markdown: basics
    • Quarto Markdown: creating
    • Quarto Markdown: publishing
    • Quarto Markdown: code & data
    • Quarto Markdown: api rest call
    • Quarto Markdown: OJS Cells
    • Quarto Markdown: cheat-sheet

    • Styling: CSS
    • Cascade Style Sheet
    • Cascade Style Sheet: Box Model and Containers
    • CSS: W3.css

    • MarkUp Languages Laboratories
    • Lab#MD01-1: Create and publish by Quarto

    • MarkUp Languages readings
    • MarkUp Languages Resources
  • Java SE
    • What is Java SE
    • Java Standard Edition: Basics
    • Java Standard Edition: Principles
    • Java MOOC Helsinki
    • Java MOOC Helsinki Syllabus

    • Java Create Project
    • Java SE: Maven
    • Java SE: Create Maven Project
    • Java SE: Project push GitHub
    • Java SE: JUnit and TDD

    • Java Concepts
    • Java SE: Class and Objects
    • Java SE: Scope
    • Java SE: static modifier
    • Java SE: Coupling and DDD
    • Java SE: Packages
    • Java SE: Abstract/Interface
    • Java SE: Java 8

    • Java Principles
    • Java SE: Encapsulation
    • Java SE: Abstraction
    • Java SE: Inherence
    • Java SE: Polymorphism

    • Java Design Patterns
    • Java Patterns: UML
    • Java Patterns: Types
    • Singleton
    • Factory
    • Abstract Factory
    • Builder
    • Facade
    • Bridge
    • Decorator
    • Composite
    • Observer
    • Strategy
    • State
    • Commander

    • Java SE Laboratories
    • Lab#SE00-1: Maven Person
    • Lab#SE00-2: Maven Clinic
    • Lab#SE00-3: Library Model
    • Lab#SE00-4: Abstract/Interface Human
    • Lab#SE01-1: Maven/Gradle Person and Account
    • Lab#SE01-2: Maven/Gradle Person and Account stored in JSON
    • Lab#SE02-1: Movie/Review, Model
    • Lab#SE02-2: Movie/Review, CRUD Operations
    • Lab#SE02-3: Movie/Review, factory
    • Lab#SE02-4: Movie/Review, interactivity and coupling
    • Lab#SE02-5: Movie/Review, simulate interactivity by console
    • Lab#SE03-1: Library/Book, Core-Model
    • Lab#SE03-2: Library/Book, Sprint Zero
    • Lab#SE03-3: Library/Book, Expand Model
    • Lab#SE04-1: healthyFood Restaurant, Core Model

    • Java SE readings
    • Java SE Resources
  • Python
    • Python Basics
    • Python: Basic Concepts
    • Python: Numbers
    • Python: Strings
    • Python: Conditionals
    • Python: Lists and Loops
    • Python: Nested Loops
    • Python: Tuples
    • Python: Sets
    • Python: Dictionaries
    • Python: Functions
    • Python: Higher-order Functions
    • Python: Variable Scope
    • Python: Variable Assigment
    • Python: None keyword in Python
    • Python: Object Oriented Programming (OOP)
    • Python: Inheritance and Polymorphism
    • Python: Encapsulation
    • Python: Abstraction
    • Python: Exceptions
    • Python: Cheat-Sheets
  • JavaScript
    • JavaScript Basics
    • JavaScript: Fundamentals
    • JavaScript: Data Types
    • JavaScript: Variables
    • JavaScript: Operators
    • JavaScript: Conditionals
    • JavaScript: Loops
    • JavaScript: Functions
    • JavaScript: Arrays
    • JavaScript: Objects

    • React Framework

    • ReactJS: Principles
    • React JS: Introduction
    • React JS: render virtual DOM
    • React JS: Create a React project
    • React JS: Components
    • React JS: JSX
    • React JS: props and state

    • JavaScript: web scripting
    • JavaScript: basics
    • JavaScript: functions
    • JavaScript: objects
    • JavaScript: variables
    • JavaScript: flux control

    • ES6: ECMAScript 6
    • React JS ES6: arrow functions
    • React JS ES6: import modules
    • React JS ES6: array, data and key
    • React JS ES6: destructuring
    • React JS ES6: spread operator

    • ReacJS 18: Hooks
    • React JS: Rules of Hooks
    • ReactJS: useState
    • React JS: useReducer
    • React JS: useRef
    • React JS: useEffect
    • React JS: useContext
    • ReactJS: useMemo
    • ReactJS: custom hooks

    • ReactJS: Designing an App
    • React JS App: async
    • React JS App: events
    • React JS App: router
    • React JS App: conditional render
    • React JS App: styling

    • React JS: Laboratories
    • Lab#RE01-1: API Rest Axios
    • Lab#RE02-1: Router & Hooks
    • Lab#RE03-1: to-do app
    • Lab#RE03-2: HighCharts
    • Lab#RE03-3: API Rest Mono
    • Lab#RE03-4: API Rest Domains
    • Lab#RE03-5: data management
    • Lab#RE04-1: todo & server
    • Lab#RE04-2: Spring Boot & ReactJS
    • Lab#RE05-1: chat & websockets
    • Lab#RE05-2: chat: backend
    • Lab#RE05-3: chat & AWS
    • Lab#RE05-4: chat: test ws AWS
    • Lab#RE05-5: chat & front
    • Lab#RE05-6: chat & ws: front
    • Lab#RE06-1: healthyFood Restaurant
    • Lab#RE06-1-PR: create a pull request
    • Lab#RE07-1: traffic lights simulation

    • React JS readings
    • ReactJS Resources
  • Backend
    • Spring Legacy
    • Spring Framework
    • Spring MVC
    • Springs Servlets

    • Spring Boot Basics
    • Spring Boot: fundamentals
    • Spring Boot: create a Project
    • Spring Boot: H2 DB and Thymeleaf
    • Spring Boot: cycle

    • Spring Boot Concepts
    • Spring Boot: Dependency Injection
    • Spring Boot: Annotations
    • Spring Boot: Controller
    • Spring Boot: View
    • Spring Boot: Thymeleaf
    • Spring Boot: Vaadin Flow
    • Spring Boot: Vaadin Hilla
    • Spring Boot: Model
    • Spring Boot: Rest
    • Spring Boot: Data & DB
    • Spring Boot: JPA & DI
    • Spring Boot: JPA Mappings
    • Spring Boot: JPA Relationships
    • Spring Boot: JPA Queries
    • Spring Boot: JPA Inherence
    • Spring Boot: Scaling

    • Spring Boot Laboratories
    • Lab#SB00-1: Library UML
    • Lab#SB00-2: CRUD User
    • Lab#SB00-3: LibraryManagement
    • Lab#SB00-4: API Rest
    • Lab#SB00-5: Rest & JPA-H2
    • Lab#SB00-6: Rest & MongoDB
    • Lab#SB00-7: Styling
    • Lab#SB01-1: DataBase
    • Lab#SB02-1: JPA Relationships
    • Lab#SB03-1: APIs & cloud
    • Lab#SB04-1: JPA Inherence
    • Lab#SB05-1: API Rest
    • Lab#SB06-1: employeeCourse
    • Lab#SB07-1: monitor Book
    • Lab#SB08-1: Restaurant UML
    • Lab#SB08-2: Vaadin
    • Lab#SB08-3: H2 and API Rest
    • Lab#SB08-4: JPA
    • Lab#SB08-5: Test API Rest
    • Lab#SB09-1: SpringIO Conference

    • Spring Boot readings
    • Spring Boot Resources
  • Learning
    • Vocabulary
    • General Vocabulary
    • SCRUM Vocabulary
    • DevOps Vocabulary
    • Java SE Vocabulay
    • Spring Boot Vocabulary
    • DataBase Vocabulary
    • ReactJS Vocabulary
    • Web Vocabulary

    • Learning
    • Useful Questions
    • Learning: tips
    • Writing
    • Taking Notes
    • Comments
    • Document
    • Auto-Evaluate

    • Books & Articles
    • Books
    • Articles

    • What is SCRUM
    • SCRUM Agile Methodology
    • Agile Manifesto & Values
    • SCRUM Guide

    • Scrum Steps
    • Meetings, Impediments and Iterations
    • User stories, Tasks and Habits
    • Delivering Value & Communication
    • ScrumMaster, how it works
    • Mindset, the key to everything
    • Product Owner, how it works
    • Managing Time & Mind
    • Team & the Specialist
    • Albertus’ Dilemma
    • Before SCRUM
    • Team Dynamics
    • Emotions and Thoughts
    • Decision Making and Intuition
    • Beyond SCRUM
    • Balances, atmosphere and tools

    • Resources
    • SCRUM Resources
  • QGIS
    • QGIS basics
    • QGIS: basic concepts

    • QGIS laboratories
    • QGIS Laboratory 1: Introduction to Open Source GIS
  • ArcGIS Pro
    • ArcGIS Pro basics
    • ArcGIS Pro: basic concepts

    • ArcGIS Pro laboratories
    • ArcGIS Pro Laboratory 1: Getting Started
  • Bookmarks
    • Online Resources
    • Online Resources
  • About
    • About me and this site
    • About me
    • About this site
    • About images credit
  • Maps
  • Featured Projects
    • ✈️ Flight tracker
    • 🧑 People tracker
    • 🚗 Renting Car
    • Email
    • GitHub
    • LinkedIn
  1. Python Basics
  2. Python: Lists and Loops
  • Python

  • Python Basics
    • Python: Basic Concepts
    • Python: Numbers
    • Python: Strings
    • Python: Conditionals
    • Python: Lists and Loops
    • Python: Nested Loops
    • Python: Tuples
    • Python: Sets
    • Python: Dictionaries
    • Python: Functions
    • Python: Higher-order Functions
    • Python: Variable Scope
    • Python: Variable Assigment
    • Python: None keyword in Python
    • Python: Object Oriented Programming (OOP)
    • Python: Inheritance and Polymorphism
    • Python: Encapsulation
    • Python: Abstraction
    • Python: Exceptions
    • Python: Cheat-Sheets

On this page

  • 1 Overview
  • 2 Lists
  • 3 Indexing and slicing
  • 4 Operations
    • 4.1 Empty
  • 5 Updating
  • 6 Adding elements
  • 7 Removing elements
    • 7.1 When to use each?
  • 8 Other list methods
  • 9 Built-in functions
  • 10 in Keyword
  • 11 Loops
    • 11.1 for
    • 11.2 List iteration example
    • 11.3 String iteration example
    • 11.4 While
  • 12 Example
  • 13 List comprehension
  • 14 Loop control statements
  • 15 Unpacking
  • 16 Unpacking
  • 17 Example
  • Edit this page
  • View source
  • Report an issue
  1. Python Basics
  2. Python: Lists and Loops

Python: Lists and Loops

Python Lists and Loops

python
lists
loops
The file system is organized into a hierarchical structure, starting with the root directory
Author

Isaac Boixaderas

Published

Sunday, June 1, 2025

Modified

Sunday, November 16, 2025

1 Overview

📘 Lists and Loops in Python

Lists in Python are mutable, ordered sequences that can hold elements of different types, support indexing, and allow modifications like adding, removing, and changing items. Loops in Python, such as for and while, are control flow constructs that repeatedly execute a block of code over collections like lists or as long as a condition is met.


2 Lists

  • Ordered collection.
  • Enclosed in square brackets and separated by commas.
  • It is allowed to store elements from multiple types.
# list of integers
my_list = [1, 4, 3, 2, 7]

# list of mixed types
my_mixed_list = [1, 'hello', 3.4, [8, 4, 6], ['a']]

3 Indexing and slicing

  • Indexing and slicing works like in strings.

List indexing in python

List indexing in python
From: https://favtutor.com/blogs/get-list-index-python

my_list = [1, 4, 3, 2, 7]

print(my_list[0])
print(my_list[-1])
print(my_list[1:4])
print(my_list[::2])
1
7
[4, 3, 2]
[1, 3, 7]

4 Operations

  • Like strings as well, with + for concatenation and * for repetition.
my_list = [1, 2, 3]

# The + operator concatenates lists
print(my_list + [8, 9, 10])
[1, 2, 3, 8, 9, 10]
# The * operator repeats lists
print(my_list * 3)
[1, 2, 3, 1, 2, 3, 1, 2, 3]

4.1 Empty

  • Check if a list is empty with len, not, and [].
# Using `len()`

my_list = []

if len(my_list) == 0:
    print("The list is empty.")
else:
    print("The list contains elements.")
The list is empty.

# Using `not`

a = []

if not a:
    print("The list is empty.")
else:
    print("The list contains elements.")
The list is empty.

# Using empty list

my_list = []

if my_list == []:
    print("The list is empty.")
else:
    print("The list contains elements.")
The list is empty.

5 Updating

  • Lists are mutable (unlike strings)!
my_list = [1, 2, 3]

# Set the first element to 8
my_list[0] = 8
print(my_list)
[8, 2, 3]

my_list = [1, 2, 3]

# Set indices 1 to 3 (not included) to 9 and 10
my_list[1:3] = [9, 10]
print(my_list)
[1, 9, 10]

6 Adding elements

We can add elements to a list using:

  • append(): Adds an element to the end of the list.

my_list = [1, 2, 3]

# The list grows as we append elements
my_list.append(4)
print(my_list)
[1, 2, 3, 4]
my_list.append(5)
print(my_list)
[1, 2, 3, 4, 5]

  • extend(): Adds multiple elements to the end of the list.
my_list = [1, 2, 3]

# The list grows as we extend it with another list
my_list.extend([7, 8, 9])
print(my_list)
[1, 2, 3, 7, 8, 9]

  • insert(): Adds an element at a specific index.
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]

# Insert element 10 at index 5 
my_list.insert(5, 10)
print(my_list)
[1, 2, 3, 4, 5, 10, 6, 7, 8, 9]

7 Removing elements

To remove elements from a list:

  • remove(): Deletes the first occurrence of a specified element.
my_list = [1, 2, 'a', 3, 2, 'b']

# Remove the first 2 you find
my_list.remove(2)
print(my_list)
[1, ‘a’, 3, 2, ‘b’]

  • It crashes if there is no equal element…
my_list = [1, 2, 'a', 3, 2, 'b']

# Remove non-existing element
my_list.remove(8)
print(my_list)
ValueError: list.remove(x): x not in list

  • pop(): Removes an element at a given index.
my_list = [1, 2, 'a', 3, 2, 'b']

# Remove the element at index 1
my_list.pop(1)
print(my_list)
[1, ‘a’, 3, 2, ‘b’]

  • If the index is not specified, it deletes the last element.
my_list = [1, 2, 'a', 3, 2, 'b']

# Remove the last element
my_list.pop()
print(my_list)
[1, 2, ‘a’, 3, 2]

  • The removed element is returned.
  • We can optionally store it in a variable.
my_list = [1, 2, 'a', 3, 2, 'b']

# The removed element is returned.
# Previously we did not use them, but they were returned as well
returned_element = my_list.pop()
print(returned_element)
print(my_list)
‘b’
[1, 2, ‘a’, 3, 2]
- `del`: Keyword that removes elements based on their index or a slice.
my_list = [1, 2, 'a', 3, 2, 'b']
# Remove the element in the given index, it is not returned
del my_list[2]
print(my_list)
[1, 2, 3, 2, ‘b’]

7.1 When to use each?

  • remove(): When you only want to remove the first occurrence of an element.
  • pop(): When you want to remove by index and preserve the value in a variable.
    • Also comfortable when you want to remove the last element.

      • del: When you want to remove by index. It is a bit more efficient than pop().
    • You could also use pop() without storing the returned value though…


8 Other list methods

Some of the most common are:

  • index(): Returns the index of the first occurrence of a specified element in the list.
my_list = [1, 2, 2, 2, 3, 4, 2, 5]

print(f'The index of the number 5 is: {my_list.index(5)}.')
print(f'The index of the first occurrence of 2 is: {my_list.index(2)}.')
The index of the number 5 is: 7.
The index of the first occurrence of 2 is: 1.

  • count(): Counts the number of occurrences of a specified element in the list.

    my_list = [1, 2, 2, 2, 3, 4, 2, 5]

print(f’The number 2 appears {my_list.count(2)} times.’)

<div class="output">The number 2 appears 4 times.</div>

***

- `sort()`: Sorts the elements of the list in-place (modifies the original list).
<!-- - `reverse()`: Reverses the elements of the list in-place (modifies the original list).
- `copy()`: Returns a copy of the list. -->

```python
my_list = [1, 2, 2, 2, 3, 4, 2, 5]

my_list.sort()
print(my_list)
[1, 2, 2, 2, 2, 3, 4, 5]

  • Extensive explanation of list methods: https://docs.python.org/3/tutorial/datastructures.html.

9 Built-in functions

Some of the most common general built-in functions for lists are:

  • len(): Returns the number of elements in a list.
  • sum(): Returns the sum of all elements in a list (for numeric lists).
  • max(): Returns the maximum value in a list.
  • min(): Returns the minimum value in a list.
  • sorted(): Returns a sorted list (does not modify the original list).

my_list = [1, 4, 2, 7, 3]

print(f'The length of the list is: {len(my_list)}.')
print(f'The sum of all the elements is: {sum(my_list)}.')
print(f'The maximum element is: {max(my_list)}.')

# Unlike the `sort()` method,
# `sorted()` returns another list without modifying the original one
print(f'The list sorted in ascending order is: {sorted(my_list)}.')
The length of the list is: 5.
The sum of all the elements is: 17.
The maximum element is: 7.
The list sorted in ascending order is: [1, 2, 3, 4, 7].

  • What is printed?
a = [1, 2, 3]
b = a
b[0] = 8

print('a =', a)
print('b =', b)

  • When setting a list as equal to another, both variables affect the same list.
a = [1, 2, 3]
b = a
b[0] = 8

# `a` and `b` are the same list
# If we change `b`, then `a` changes as well
print('a =', a)
print('b =', b)
a = [8, 2, 3]
b = [8, 2, 3]

  • If we want independent lists we can use the copy() method:
a = [1, 2, 3]
# Make a copy of `a` and assign it to `b`
b = a.copy()
b[0] = 8

# If we change `b`, then `a` does not change
print('a =', a)
print('b =', b)
a = [1, 2, 3]
b = [8, 2, 3]

10 in Keyword

  • Can be used for checking if a specific value is inside the sequence.
  • It also has a special usage in “for loops” (next slides).
fruits = ['apple', 'banana', 'cherry', 'orange', 'kiwi', 'melon']

print('apple' in fruits)
True
print('pear' in fruits)
False

11 Loops

  • Essential in programming.
  • They allow us to execute a block of code repeatedly.
  • Python supports two types: for and while loops.

11.1 for

  • Iterate over a sequence, such as a list or a string.

  • Syntax:

    for [variable_name] in [iterable_sequence]:
      code block

11.2 List iteration example

my_list = [1, 2, 3]

for element in my_list:
    # This goes over each element in the list,
    # executing this code block for each one
    print(element)
1
2
3

Commonly used built-in functions for for loops:

  • enumerate(): Gives back two variables: the count of the current iteration and the value of the item at the current iteration.
# With the enumerate function we get the:
#       index (iteration count)
#       value of each element

my_list = [3, 2, 1]

for index, value in enumerate(my_list):
    print(f'The element at index {index} is {value}.')
The element at index 0 is 3.
The element at index 1 is 2.
The element at index 2 is 1.

  • range(): Sequence of numbers. By default, starts from 0 and increments by 1. Stops before a specified number.
# It starts at 0 (default) and ends at 4 (not included)
for i in range(4):
    print(i)
0
1
2
3

# Starts at 2 and ends at 6 (not included)
for i in range(2, 6):
    print(i)
2
3
4
5

# Starts at 0 and ends at 10 (not included), in increments of 2
for i in range(0, 10, 2):
    print(i)
0
2
4
6
8

11.3 String iteration example

my_list = "Hello"

for character in my_list:
    # This goes over each character in the string
    print(character)
H
e
l
l
o

11.4 While

  • Executes an iteration if condition remains True.

  • Syntax:

    while [condition]:
      code block

count = 0
while count < 4:
    print(f'{count} is less than 4.')
    count += 1

print(f'The loop ended because {count} is greater or equal to 4.')
0 is less than 4.
1 is less than 4.
2 is less than 4.
3 is less than 4.
The loop ended because 4 is greater or equal to 4.

  • We can chain as many conditions as we want:
count = 0
while count < 4 and count * 3 < 8:
    print(f'{count} is less than 4 and {count * 3} is less than 8.')
    count += 1

print(f'{count} is greater or equal to 4 or {count * 3} is greater than 8.')
0 is less than 4 and 0 is less than 8.
1 is less than 4 and 3 is less than 8.
2 is less than 4 and 6 is less than 8.
3 is greater or equal to 4 or 9 is greater than 8.

  • Take care of infinite loops!
  • If the specified condition is never met, while will execute forever…
  • Raising a Python error (maybe after some time!).
# Do not run this
a = 5
while a < 10:
    print('Hi')
Error because of infinite loop

12 Example

  • Create a list that contains the squares of the first 5 integers.
# Squares of the first 5 integers
squares = []

for x in range(1, 6):
    squares.append(x**2)

print(squares)
[1, 4, 9, 16, 25]

13 List comprehension

List comprehension is a concise way to create a new list by performing an operation on every element of an existing iterable (like a list, tuple, or range). It can also include a condition to filter which items are included. The Syntax:

newlist = [expression for item in iterable if condition == True]

*The return value is a new list, leaving the old list unchanged.

  • expression: What you want to do with each item (e.g., multiply by 2).
  • item: The current element from the iterable.
  • iterable: The list, range, or other object you are looping over.
  • if condition: (optional) Only include items that meet this condition.
# Squares of the first 5 integers
squares = [x**2 for x in range(1, 6)]
print(squares)
[1, 4, 9, 16, 25]

{pyodide-python numbers = [1, 2, 3, 4] doubled_numbers = [num * 2 for num in numbers] print(doubled_numbers)

[2, 4, 6, 8]

In this example, num * 2 is the expression, num is each item from numbers, and numbers is the iterable.

# With an `if` condition

# Squares of the first 5 even integers
even_squares = [x**2 for x in range(1, 6) if x % 2 == 0]
print(even_squares)
[4, 16]

14 Loop control statements

Allow us to change the flow of loops during execution.

Keywords:

  • break: Terminates the current loop.
  • continue: Skips the remaining code in the current iteration and proceeds to the next one.

# `break` example

for num in range(10):
    if num == 5:
        # Break the loop
        break
    print(num)
print('Outside the loop')
0
1
2
3
4
Outside the loop

# `continue` example

for num in range(10):
    if num % 2 == 0:
        # Skip the rest of the code in this iteration,
        # going to the next iteration
        continue
    print(num)
print('Outside the loop')
1
3
5
7
9
Outside the loop

15 Unpacking

  • Taking the elements of a collection (list, string…) and assigning them to variables.
l = [3, 4]
a, b = l

print(a)
print(b)
3
4

16 Unpacking

  • Another example with strings.
x, y, z = 'hey'

print(x)
print(y)
print(z)
h
e
y

17 Example

  • Write a program that finds the common elements between two lists with the same length.

  • Input:

    • list1 = [1, 2, 3, 4, 5]
    • list2 = [4, 5, 6, 7, 8]
  • Output:

    • [4, 5]

list1 = [1, 2, 3, 4, 5]
list2 = [4, 5, 6, 7, 8]
common_elements = []

for element in list1:
    if element in list2:
        common_elements.append(element)

print(common_elements)
Back to top
Python: Conditionals
Python: Nested Loops

License: CC0 1.0 Universal

Per aspera, ad astra

  • Edit this page
  • View source
  • Report an issue