I didn’t think much about Robot Framework’s loops until a test suite became impossible to maintain.
One small update meant editing the same steps in multiple places, and every change introduced new mistakes. Something wasn’t scaling—and loops turned out to be the missing piece.
Once I explored how Robot Framework iterates through lists, dictionaries, and ranges, I realized I could replace entire sections of duplicated steps with a few clean, flexible loops. It changed how I approached automation entirely.
Overview
Basic Syntax of ‘For Loop’ in Robot Framework:
FOR ${item} IN @{list}
<keywords using ${item}>
END- And the structure explained:
- FOR begins the loop
- ${item} is the loop variable
- IN specifies the sequence
- @{list} is the collection being iterated
- Indented keywords run for each item
- END closes the loop
Types of For Loop in Robot Framework:
- FOR IN Loop: Best for validating multiple inputs, repeating UI steps, or processing datasets.
- FOR IN RANGE Loop: Useful for fixed repetitions, stress tests, and index-based operations.
- FOR IN ZIP Loop: Ideal for validating input–output pairs or mapping fields to expected values.
- FOR IN ENUMERATE Loop: Valuable for table validations, row-based checks, or debugging list content.
This guide walks through how those loops actually work, with practical examples and patterns that make test automation faster and far easier to manage.
What is the Robot Framework?
Robot Framework is an open-source automation framework designed for test automation and robotic process automation (RPA).
It uses a simple, keyword-driven syntax that makes creating and managing test cases easy, even for users with minimal programming knowledge. It’s widely used for user acceptance testing, UI testing, and integration testing across different platforms and technologies.
What is the Purpose of For loops in Robot Framework?
The for loop Robot framework is to automate repetitive tasks, reduce manual effort, and make test scripts more efficient and maintainable.
For loops in Robot Framework can be used in various scenarios, such as iterating over a list of test data values to run the same test case with different input parameters or iterating over a set of UI elements to perform the same action on each element.
Key factors for using For loop in Robot Framework:-
- For loops are used to iterate over a sequence of values or items in Robot Framework.
- For loops can be nested, allowing multiple levels of iteration.
- For loops are commonly used in Robot Framework to automate repetitive tasks, such as iterating over a list of test data or UI elements.
- By using For loops, test scripts can be made more efficient, maintainable, and less prone to errors.
- For loops can also be used with conditional statements, allowing for more complex control flow in test scripts.
- For loops can also be used with user-defined keywords to perform a sequence of actions for each item.
- The Continue For Loop If and Exit For Loop If keywords can be used to control the flow of a for loop based on a condition.
- For loops can be used to iterate over a sequence of files or directories, allowing for file operations or data processing.
- The ELSE statement can be used in a for loop to execute actions if the loop completes without interruption.
- Loops can generate and verify test data or create dynamic test cases based on input parameters.
How to write a for loop in Robot Framework?
A FOR loop in Robot Framework is a control structure that allows us to repeat a set of actions a certain number of times, or to iterate over a list or range of values.
The basic syntax of a robot framework for loop example is as follows:
*** Variables ***
@{list} item1 item2 item3
*** Test Cases ***
Example Test
FOR ${item} IN @{list}
Log ${item}
# Perform other actions on ${item}
END- In this example, the FOR loop statement is used to iterate over the @{list} variable.
- Within the loop, the ${item} variable is set to each item in the list and printed using the Log keyword.
- Replace the “log” keyword with any other keyword to perform different actions on each item in the list.
You can also use Python’s built-in range function to iterate a specific number of times. Here is an example:
*** Test Cases ***
Example Test
FOR ${i} IN RANGE 5
Log ${i}
END- In this example, the FOR loop statement is used with the RANGE keyword to iterate five times, and the ${i} variable is set to the index of each iteration.
- The Log keyword is used to print the index of each iteration.
- You can replace the Log keyword with any other keyword to perform different actions within the loop.
Basic Syntax of For Loops in the Robot Framework
Robot framework for loop is used to repeat a set of steps a certain number of times or for a specific range of values.
The basic syntax for a for loop robot framework is as follows:
FOR ${index} IN RANGE ${start} ${end} [${step}]
[Keyword or Steps]
[Keyword or Steps]
[Keyword or Steps]- ${index}: A user-defined variable to store the current value of the loop iteration.
- IN RANGE: A keyword used to specify the range of values for the loop.
- ${start}: The starting value of the range.
- ${end}: The ending value of the range.
- ${step} (optional): The increment between each loop iteration. The default is 1.
- Data-driven testing: For loops can be used to iterate through a set of test data and execute the same test steps with different data sets.
For example, if we have a list of usernames and passwords to test login functionality, we can use a for loop to iterate through the list and execute the login test with each set of credentials.
FOR ${user} ${password} IN ZIP @{usernames} @{passwords}
Input Text ${username_field} ${user}
Input Text ${password_field} ${password}
Click Button ${login_button}
Wait Until Page Contains ${welcome_message}
Click Button ${logout_button}- Processing lists or tables: It can process a list or table of data and perform the same actions on each item in the list or table.
For example, if we have a list of products and their prices, we can use a for loop to calculate the total cost of all the products.
FOR ${product} ${price} IN ZIP @{products} @{prices}
${subtotal} = Evaluate ${price} * ${quantity}
${total} += ${subtotal}- Generating test data: It can be used to generate test data and execute test cases with the generated data.
For example, if a test case requires a unique email address each time it is executed, we can use a for loop to generate a list of unique email addresses and execute the test case with each email address.
FOR ${i} IN RANGE 1 ${number_of_tests}
${email} = Generate Unique Email
Run Keyword And Continue On Failure Submit Registration Form ${email} ${password}- Repeating actions a fixed number of times: It can be used to repeat a set of actions a fixed number of times. For example, if we need to execute a set of test steps 10 times to test stability and performance, we can use a for loop to repeat the set of steps 10 times.
FOR ${i} IN RANGE 1 10
Click Button ${random_button}
Wait Until Page Contains Element ${random_element}
Click Button ${back_button}These are just a few examples of the many ways for loops can be used in Robot Framework for real-time use cases. The versatility of the for loop syntax allows us to apply them in a wide range of testing scenarios.
Types of For Loops in Robot Framework
Robot Framework supports multiple loop variations, each designed for specific data structures and iteration needs. Below are the four core loop types, with details on when and why each is used.
FOR IN Loop
The FOR IN loop is the most commonly used loop type and is ideal for iterating over lists, tuples, or any collection of values. It allows executing the same set of keywords for every item in a sequence. This loop is often used for validating multiple inputs, running repeated UI interactions, or processing datasets. Its flexibility makes it the default choice for most test scenarios where items need to be handled individually.
*** Test Cases ***
For In Example
@{items}= Create List Apple Banana Orange
FOR ${item} IN @{items}
Log ${item}
ENDFOR IN RANGE Loop
The FOR IN RANGE loop is used when a test requires fixed repetition or numeric iteration. It behaves similarly to Python’s range() function, generating a series of integers from a starting point to an endpoint. This loop is helpful for running a specific number of retries, executing stress tests with repeated actions, or performing index-based operations without relying on an existing list.
*** Test Cases ***
For In Range Example
FOR ${i} IN RANGE 0 5
Log Iteration ${i}
ENDFOR IN ZIP Loop
The FOR IN ZIP loop allows simultaneous iteration over two or more lists, pairing elements based on their position. This is especially useful for validating input–output pairs, combining UI fields with expected results, or driving test steps where related data must be processed together. If one list is shorter, the loop stops at the end of the shortest sequence, ensuring synchronized iteration.
*** Test Cases ***
For In Zip Example
@{names}= Create List John Sara Alex
@{roles}= Create List Admin Editor Viewer
FOR ${name} ${role} IN ZIP @{names} @{roles}
Log ${name} has role ${role}
ENDFOR IN ENUMERATE Loop
The FOR IN ENUMERATE loop provides both the index and the value of each element in the list. It is suited for scenarios where the position of the item matters—such as validating table rows, generating dynamic identifiers, or debugging test data issues. The index can also be used to trigger conditional logic, making this loop type useful for more advanced flow control inside test cases.
*** Test Cases ***
For In Enumerate Example
@{items}= Create List Alpha Beta Gamma
FOR ${index} ${item} IN ENUMERATE @{items}
Log Index: ${index}, Item: ${item}
ENDRead More: Best 18 Test Automation Frameworks in 2025
Using For Loops with Lists in the Robot Framework
In the Robot Framework, you can use For Loops with lists using the built-in FOR loop construct in combination with Python code. Here’s an example of how to do this:
Define your list in a test case or keyword:
*** Test Cases ***
Example Test Case
${my_list}= Create List item1 item2 item3
FOR ${item} IN @{my_list}
Log ${item}
ENDIn the above example, the Create List keyword creates a list with items item1, item2, and item3. The FOR loop then iterates through each item in the list and logs the item to the console.
You can also use Python code within the FOR loop to manipulate the list items:
*** Test Cases ***
Example Test Case
${my_list}= Create List item1 item2 item3
FOR ${item} IN @{my_list}
Log ${item}
END- In the above example, the Create List keyword creates a list with three items: 1, 2, and 3.
- The FOR loop then iterates through each item in the list using the RANGE keyword, which generates a range of values from 0 to the length of the list.
- The Python code within the loop multiplies each item by 2, effectively doubling its value. Finally, the Log List keyword logs the modified list to the console.
Note that the ${} syntax is used to access variables in Robot Framework. In the Python code within the FOR loop, the ${index} variable is used to access the current index of the list, and the ${my_list[${index}]} syntax is used to access the value of the list item at the current index.
Using For Loops with Dictionaries in Robot Framework
With Robot Framework, you can use the built-in FOR loop construct in combination with Python code for loops with dictionaries. Here’s an example of how to do this:
Define your dictionary in a test case or keyword:
*** Test Cases ***
Example Test Case
${my_dict}= Create Dictionary key1=value1 key2=value2 key3=value3
FOR ${key} IN @{my_dict.keys()}
${value}= Set Variable ${my_dict[${key}]}
Log Key: ${key} Value: ${value}
END- In the above example, the Create Dictionary keyword creates a dictionary with three key-value pairs.
- The FOR loop then iterates through each key in the dictionary using the keys() method and sets the corresponding value to a variable using the ${my_dict[${key}]} syntax.
- The Log keyword then logs both the key and value to the console.
You can also use Python code within the FOR loop to manipulate the dictionary items:
*** Test Cases ***
Example Test Case
${my_dict}= Create Dictionary key1=1 key2=2 key3=3
FOR ${key} IN @{my_dict.keys()}
${my_dict[${key}]}= Set Variable ${my_dict[${key}]} * 2
END
Log Dictionary ${my_dict}- In the above example, the Create Dictionary keyword creates a dictionary with three key-value pairs.
- The FOR loop then iterates through each key in the dictionary using the keys() method.
- The Python code within the loop multiplies each value by 2, effectively doubling its value.
- Finally, the Log Dictionary keyword logs the modified dictionary to the console.
Note that the ${} syntax is used to access variables in Robot Framework. In the Python code within the FOR loop, the ${key} variable is used to access the current key of the dictionary, and the ${my_dict[${key}]} syntax is used to access the value of the dictionary item at the current key.
Nesting For Loops in Robot Framework
A nested for loop is a loop inside another loop. In programming, it allows you to iterate through multiple lists or items at once by going through the outer loop first, then through the inner loop for each iteration of the outer loop.
You can nest for loops in Robot Framework using the built-in FOR construct. This allows you to iterate over multiple lists or data sets at the same time.
Here’s an example of how to do this:
*** Test Cases ***
Example Test Case
@{list1}= Create List 1 2 3
@{list2}= Create List A B C
FOR ${item1} IN @{list1}
Log Outer loop item: ${item1}
FOR ${item2} IN @{list2}
Log Inner loop item: ${item2}
END
END- In this example of nest For loop, the Create List keyword is used to create two lists, list1 and list2, each with three items.
- The outer FOR loop iterates through each item in list1, and the inner FOR loop iterates through each item in list2.
- The Log keyword is then used to print each item to the console.
When nesting FOR loops, include an END statement for each loop. The inner FOR loop must be closed before the outer FOR loop. You can also use Python code within the loops to perform more complex operations.
*** Test Cases ***
Example Test Case
@{list1}= Create List 1 2 3
@{list2}= Create List A B C
FOR ${item1} IN @{list1}
Log Outer loop item: ${item1}
FOR ${item2} IN @{list2}
${result}= Run Keyword And Return Status Should Contain ${item2} ${item1}
Run Keyword If '${result}' == 'True' Log Inner loop item: ${item2}
END
END- Here, the Should Contain keyword checks if ${item2} contains ${item1}.
- The Run Keyword If a keyword is then used to check if the previous keyword returned True.
- If so, the Log keyword prints ${item2} to the console. This demonstrates how you can use for loops to perform more complex operations in your test cases.
Running nested loops often means executing complex test flows across multiple environments. BrowserStack Automate makes this scalable by running each loop iteration on real browsers and OS combinations, helping teams uncover UI and workflow issues that only appear in real user conditions.
Real-World Use Cases & Examples of ‘For Loop’ in Robot Framework
For loops in Robot Framework are widely used to handle repetitive validations, iterate through datasets, and execute the same action across multiple environments or input values. The examples below illustrate how loops solve real testing problems across UI, API, and data-driven scenarios.
Validating Multiple Form Fields
When a page contains several input fields, a loop allows validating each field without duplicating steps.
*** Test Cases ***
Validate Multiple Form Fields
Open Browser https://example.com/form chrome
@{fields}= Create List username email phone
FOR ${field} IN @{fields}
Element Should Be Visible id=${field}
Element Should Be Enabled id=${field}
END
Close BrowserThis avoids three separate test blocks and centralizes the validation.
Running the Same UI Test Across Multiple Browsers
A single for loop can cycle through different BrowserStack environments to catch cross-browser issues early.
*** Test Cases ***
Cross Browser Test
@{browsers}= Create List chrome firefox edge
FOR ${browser} IN @{browsers}
Open Browser https://shop.com ${browser}
Page Should Contain Shop Now
Close Browser
ENDTeams often use this pattern with BrowserStack Automate to scale multi-browser testing.
Data-Driven API Testing
Testing multiple payloads becomes simple with a loop.
*** Test Cases ***
API Payload Validation
@{payloads}= Create List {"id":1} {"id":2} {"id":3}
FOR ${payload} IN @{payloads}
${response}= Post Request api /user ${payload}
Should Be Equal As Integers ${response.status_code} 200
ENDThis reduces repeated API test cases and simplifies updates.
Verifying Table Rows
Loops help validate dynamic tables where the number of rows can change.
*** Test Cases ***
Validate Table Rows
@{rows}= Get WebElements //table/tbody/tr
FOR ${row} IN @{rows}
${text}= Get Text ${row}
Should Not Be Empty ${text}
ENDThis works well for dashboards, reports, and admin panels.
Bulk Upload or Multi-Step Flows
If the test must upload multiple files or repeat a workflow, a loop makes the sequence clean and reusable.
*** Test Cases ***
Upload Multiple Files
@{files}= Create List file1.png file2.pdf file3.jpg
FOR ${file} IN @{files}
Choose File id=upload ${CURDIR}/${file}
Click Button id=submit
Page Should Contain Upload Successful
ENDGreat for regression tests involving multiple data samples.
Stress Testing with Range Loops
A FOR IN RANGE loop helps repeat an action more times than manually practical.
*** Test Cases ***
Stress Test Login
FOR ${i} IN RANGE 1 20
Attempt Login With Invalid Credentials
Page Should Contain Invalid username or password
ENDUseful for negative testing and rate-limiting validations.
Controlling the execution of a for loop manually
In Robot Framework, you can manually control the flow of a FOR loop using built-in keywords. This allows you to determine when to skip specific iterations or exit the loop early based on custom conditions.
Similar to traditional programming languages like Python, where break and continue statements are used to manage loop execution, Robot Framework provides equivalent keywords:
- Exit For Loop If — Terminates the loop early if a given condition is met.
- Continue For Loop If — Skips the current iteration and proceeds to the next one if the condition is evaluated as true.
These keywords help optimize test cases by avoiding unnecessary steps or iterations, especially when specific criteria are already satisfied or invalid.
Example:
FOR ${item} IN @{list}
${result}= Run Keyword And Return Status Should Be Equal ${item} foo
Continue For Loop If ${result}
Log ${item}
Exit For Loop If '${item}' == 'bar'
ENDIn this example:
- Continue For Loop If skips the current iteration if ${item} is equal to “foo”.
- Exit For Loop If stops the loop entirely if ${item} equals “bar”.
Read More: Robot Framework and Selenium Test Automation
Common Issues and Troubleshooting the For Loop
Several common issues may arise while using FOR loops in Robot Framework, especially if you’re new to it.
1. Incorrect Indentation
Robot Framework is indentation-sensitive. If the loop body is not correctly indented under the FOR keyword, the loop may not execute as expected or could throw an error.
Fix: Ensure all keywords inside the loop are consistently indented and aligned under the FOR block.
2. Missing END Statement (Robot Framework 4.0+)
From Robot Framework 4.0 onwards, loops require an explicit END to indicate the end of the loop body.
Fix: Always add an END statement after the last keyword in the loop.
3. Improper List or Variable Usage
Trying to iterate over an undefined or improperly formatted list can cause the loop to fail.
Fix: Ensure the list is defined correctly and initialized before the loop. Use @{list} syntax for lists.
4. Incorrect Loop Syntax
Using outdated or mixed syntax (such as forgetting IN, or misplacing variables) can lead to execution errors.
Fix: Use the correct format:
FOR ${item} IN @{list}
Log ${item}
END5. Unintended Infinite Loop Behavior
While Robot Framework doesn’t support traditional while loops, incorrect use of control keywords like Exit For Loop If may cause loops to behave unexpectedly or never exit.
Fix: Double-check the conditions used in the Exit For Loop If to ensure they trigger when expected.
6. Data Type Mismatches
Comparisons in loop conditions can fail silently if the data types are inconsistent, such as comparing a number to a string.
Fix: Ensure that the values being compared are of compatible types. Use type conversion if needed.
Best Practices for Using For Loops in Robot Framework
Follow these best practices when using for loops in Robot Framework to enhance your test case.
- Keep it simple: The most effective use of for loops is when the iteration logic is simple and easy to understand. Complex or convoluted iteration logic can make your code harder to read and debug.
- Use descriptive variable names: Use variable names that clearly describe what the variable represents. This can make our code more readable and help prevent errors.
- Limit the scope of variables: It’s generally a good idea to limit the scope of variables used in for loops to the loop itself. This can help prevent naming conflicts and make our code easier to understand.
- Avoid modifying the list during iteration: Modifying the list being iterated over during the iteration can lead to unexpected behavior and errors. If we need to modify the list, consider creating a copy before iterating.
- Use the range() function for iterating over indices: When iterating over a list and needing the index of each item, use the range() function. This allows us to iterate over the indices of the list instead of the values themselves.
- Use built-in keywords whenever possible: Robot Framework provides several built-in keywords for iterating over lists and dictionaries. Whenever possible, use these keywords instead of implementing your iteration logic.
- Test thoroughly: As with any code, it’s important to test our for loops thoroughly to ensure they are working as expected. Test cases should include edge and negative scenarios to ensure your code is robust and error-free.
Loops vs. User-Defined Keywords in Robot Framework
Loops in Robot Framework are used when test steps need to be repeated for multiple inputs, datasets, or environments. They are ideal for iterating through lists, ranges, or paired values and help eliminate repeating the same keyword sequence multiple times. Loops shine in data-driven scenarios—validating form fields, checking multiple API payloads, or running the same UI interactions across different browsers.
User-defined keywords, on the other hand, are best suited for grouping related steps into a reusable unit. They help organize test cases, reduce clutter, and maintain logic in one place instead of repeating long sequences. Keywords make the test suite more readable and allow central updates: changing one keyword updates every test that uses it.
In practice, loops and user-defined keywords work best together. A loop handles iteration, while the repeated steps inside it are packaged into a clean, reusable keyword. This approach keeps tests scalable, easier to maintain, and far less error-prone.
Loops vs. User-Defined Keywords in Robot Framework
| Aspect | Loops | User-Defined Keywords |
|---|---|---|
| Purpose | Repeat a set of steps for multiple items or iterations | Group related steps into reusable, maintainable keywords |
| Best Use Case | Data-driven testing, iterating over lists, ranges, or paired values | Organizing workflows, reducing duplication, improving readability |
| When to Choose | When the same action must run multiple times with different inputs | When steps form a logical unit that appears in multiple tests |
| Advantages | Eliminates repetitive blocks, supports dynamic input processing | Centralized logic, cleaner test cases, easier updates |
| Limitations | Can become hard to read if loops grow complex or nested | Not ideal for large sets of repetitive actions without loops |
| Typical Pattern | Loop iterates → keywords execute inside each iteration | Keyword encapsulates logic → can be called inside loops |
| Ideal Together | Run loops for iteration across datasets | Use keywords to keep loop content clean and reusable |
Conclusion
For loops in Robot Framework help automate repetitive actions by allowing you to iterate over lists, dictionaries, or other sequences without duplicating code. Instead of writing the same set of steps multiple times, you can use a loop to execute them dynamically for each input. This reduces redundancy, improves readability, and makes test cases easier to update and scale.
Run your Robot Framework tests on real browsers and devices using BrowserStack Automate to validate them under real-world conditions. With support for parallel execution, CI/CD integration, and debugging tools like video logs and screenshots, BrowserStack enables faster, more accurate testing at scale.