Master ‘For Loops’ in Robot Framework

Related Product On This Page What is the Robot Framework?May 27, 2026 · 22 min read · Testing Guide

Related Product

How to use for iteration in Robot Framework in 2026

I didn ’ t imagine much about Robot Framework ’ s loops until a test retinue became impossible to maintain.

One minor update meant editing the same steps in multiple places, and every modification introduced new mistakes. Something wasn ’ t scaling—and grummet turned out to be the missing part.

Once I explored how Robot Framework iterates through lists, dictionary, and ranges, I realized I could supersede entire sections of duplicated steps with a few clean, pliant loops. It change how I approached automation entirely.

Overview

Basic Syntax of ‘ For Loop ’ in Robot Framework:

FOR $ {detail} IN @ {lean} & lt; keywords using $ {item} & gt; END
  • And the structure explained:
  • FOR begins the loop
  • $ {item} is the cringle variable
  • IN specifies the sequence
  • @ {inclination} 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 process 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 field to expected value.
  • FOR IN ENUMERATE Loop: Valuable for table validations, row-based checks, or debugging list message.

This usher walk through how those loops actually work, with practical examples and patterns that do test automation faster and far easy to manage.

What is the Robot Framework?

is an open-source mechanisation model designed for exam automation and robotic process automation (RPA).

It uses a simple, keyword-driven syntax that makes make and managing trial example easy, even for exploiter with minimal programming cognition. It & # 8217; s widely used for,, and across different platforms and engineering.

What is the Purpose of For loops in Robot Framework?

The for loop Robot fabric is to automatise repetitive tasks, reduce manual sweat, and make trial playscript more effective and maintainable.

For loops in Robot Framework can be expend in various scenario, such as restate over a list of test information values to run the same test lawsuit with different remark argument or restate over a set of UI elements to perform the like action on each element.

Key factors for using For cringle in Robot Framework: -

  • For loops are used to iterate over a sequence of value or items in Robot Framework.
  • For loops can be nested, allowing multiple levels of iteration.
  • For loops are normally used in Robot Framework to automate repetitive tasks, such as iterating over a list of tryout data or UI elements.
  • By using For loops, test scripts can be made more efficient, maintainable, and less prone to error.
  • For loops can also be used with conditional statements, allowing for more complex control flow in test scripts.
  • For cringle can also be used with user-defined keywords to perform a successiveness 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 cringle based on a condition.
  • For loops can be employ to restate over a sequence of files or directory, allowing for file operation or data processing.
  • The ELSE argument can be used in a for eyelet to execute actions if the loop complete without interruption.
  • Loops can give and control test data or make dynamic test case found on input parameters.

Want stable Robot runs?

Use BrowserStack to validate loop-driven tryout on real browsers

How to write a for iteration in Robot Framework?

A FOR loop in Robot Framework is a control construction that allows us to repeat a set of actions a certain routine of times, or to retell over a list or reach of values.

The basic syntax of a golem framework for loop model is as follow:

* * * Variables * * * @ {list} item1 item2 item3 * * * Test Cases * * * Example Test FOR $ {item} IN @ {list} Log $ {detail} # Perform other actions on $ {item} END
  • In this example, theFORloop statement is used to iterate over the@{list} variable.
  • Within the loop, the${item}variable is set to each detail in the list and publish using the Log keyword.
  • Replace the & # 8220; log & # 8221; keyword with any early keyword to perform different activeness on each item in the tilt.

You can also use Python & # 8217; s built-in scope function to iterate a specific routine of times. Here is an example:

* * * Test Cases * * * Example Test FOR $ {i} IN RANGE 5 Log $ {i} END
  • In this illustration, the FOR loop statement is employ with the RANGE keyword to iterate five times, and the $ {i} variable is set to the index of each loop.
  • The Log keyword is apply to publish the indicator of each iteration.
  • You can supplant 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 employ to repeat a set of measure a certain number of times or for a specific range of values.

The basic syntax for a for loop robot framework is as follow:

FOR $ {index} IN RANGE $ {start} $ {end} [$ {stride}] [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 ambit.
  • ${end}:The ending value of the orbit.
  • $ {pace} (optional):The increment between each eyelet iteration. The default is 1.
  • Data-driven testing:For loops can be used to reiterate through a set of exam datum and execute the same test steps with different information sets.

For example, if we receive a list of usernames and passwords to try login functionality, we can use a for iteration to iterate through the listing and execute the login test with each set of credentials.

FOR $ {user} $ {word} IN ZIP @ {usernames} @ {passwords} Input Text $ {username_field} $ {user} Input Text $ {password_field} $ {word} 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 datum and perform the same actions on each item in the tilt 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} $ {terms} IN ZIP @ {products} @ {prices} $ {subtotal} = Evaluate $ {price} * $ {quantity} $ {full} += $ {subtotal}
  • Generating test datum:It can be utilise to generate test data and execute with the generated datum.

For example, if a test case requires a unique e-mail address each time it is executed, we can use a for loop to give a list of unique email addresses and accomplish the test example 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 $ {e-mail} $ {parole}
  • Repeating actions a fixed number of times:It can be used to repeat a set of actions a fixed number of clip. For exemplar, if we need to execute a set of test steps 10 time to test stability and execution, 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 style for eyelet can be used in Robot Framework for real-time use cases. The versatility of the for loop syntax let us to hold them in a wide range of testing scenario.

Types of For Loops in Robot Framework

Robot Framework supports multiple loop fluctuation, each plan for specific data structure and loop needs. Below are the four nucleus loop types, with details on when and why each is used.

FOR IN Loop

The FOR INgrommet is the almost commonly used loop type and is ideal for iterating over listing, tuples, or any collection of values. It allows executing the same set of keywords for every particular in a sequence. This iteration is often use for validating multiple remark, pass repeated UI interactions, or process datasets. Its flexibility makes it the default choice for most test scenarios where item demand to be handled severally.

* * * Test Cases * * * For In Example @ {items} = Create List Apple Banana Orange FOR $ {item} IN @ {items} Log $ {item} END

FOR IN RANGE Loop

The FOR IN RANGEgrommet is employ when a test requires fixed repetition or numerical iteration. It behave likewise to Python ’ s range () function, generating a serial of integers from a starting point to an endpoint. This loop is helpful for running a specific number of retries, action stress tests with repeated actions, or perform index-based operation without trust on an existing list.

* * * Test Cases * * * For In Range Example FOR $ {i} IN RANGE 0 5 Log Iteration $ {i} END

FOR IN ZIP Loop

The FOR IN ZIPloop allows simultaneous iteration over two or more lists, pairing elements based on their view. 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 block at the end of the shortest succession, ensuring synchronized iteration.

* * * Test Cases * * * For In Zip Example @ {name} = Create List John Sara Alex @ {roles} = Create List Admin Editor Viewer FOR $ {gens} $ {role} IN ZIP @ {name} @ {use} Log $ {gens} has role $ {role} END

FOR IN ENUMERATE Loop

The FOR IN ENUMERATEloop provides both the index and the value of each element in the list. It is suited for scenario where the position of the item matters—such as corroborate table quarrel, generating dynamical identifiers, or debugging test data topic. The index can likewise be used to trigger conditional logic, making this loop eccentric utile for more advanced flow control inside tryout cases.

* * * Test Cases * * * For In Enumerate Example @ {particular} = Create List Alpha Beta Gamma FOR $ {index} $ {detail} IN ENUMERATE @ {items} Log Index: $ {indicator}, Item: $ {particular} END

Read More:

Using For Loops with Lists in the Robot Framework

In the Robot Framework, you can use For Loops with lists habituate the built-in FOR loop construct in combination with Python codification. 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} END

In the above exemplar, the Create List keyword creates a list with detail item1, item2, and item3. The FOR loop then iterate through each particular in the inclination and logs the particular to the console.

You can also use Python code within the FOR grommet to manipulate the list items:

* * * Test Cases * * * Example Test Case $ {my_list} = Create List item1 item2 item3 FOR $ {point} IN @ {my_list} Log $ {item} END
  • In the above representative, the Create List keyword creates a list with three items: 1, 2, and 3.
  • The FOR loop so retell through each item in the listing using the RANGE keyword, which generates a range of values from 0 to the length of the list.
  • The Python codification within the loop multiplies each point by 2, effectively doubling its value. Finally, the Log List keyword logs the limited listing to the console.

Note that the ${}syntax is used to access variable in Robot Framework. In the Python code within the FOR loop, the $ {index} variable is used to approach the current power of the list, and the$ {my_list [$ {index}]}syntax is used to access the value of the list detail 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 lawsuit 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

For autonomous testing across multiple user personas, check out SUSATest — it explores your app like 10 different real users.

  • In the above illustration, the Create Dictionary keyword creates a dictionary with three key-value pairs.
  • The FOR grommet so iterates through each key in the dictionary using the key () method and sets the corresponding value to a variable utilise the$ {my_dict [$ {key}]}syntax.
  • The Log keyword then logs both the key and value to the console.

You can too use Python codification within the FOR grommet 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 create a dictionary with three key-value pairs.
  • The FOR loop then iterates through each key in the dictionary using the keys () method.
  • The Python codification within the loop multiplies each value by 2, efficaciously doubling its value.
  • Finally, the Log Dictionary keyword lumber the limited 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 entree the value of the dictionary point at the current key.

Nesting For Loops in Robot Framework

A nested for loop is a loop inside another eyelet. In programming, it allows you to iterate through multiple lists or items at formerly by going through the outer loop firstly, 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 inclination or data sets at the same time.

Here & # 8217; 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 particular: $ {item2} END END
  • In this exemplar of nest For loop, the Create List keyword is used to create two lists, list1 and list2, each with three particular.
  • The outer FOR loop iterates through each item in list1, and the inner FOR loop iterates through each detail in list2.
  • The Log keyword is then used to print each point to the console.

When nesting FOR loops, include an END statement for each iteration. 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 point: $ {item1} FOR $ {item2} IN @ {list2} $ {result} = Run Keyword And Return Status Should Contain $ {item2} $ {item1} Run Keyword If ' $ {result} ' == 'True ' Log Inner loop point: $ {item2} END END
  • Here, theShould Containkeyword checks if${item2} contains ${item1}.
  • The Run Keyword If a keyword is so used to insure 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 execute more complex operations in your test causa.

Running nested loops often means fulfill complex test feed across multiple environments. do this scalable by pass each loop iteration on real browsers and OS combinations, helping teams uncover UI and workflow issues that only appear in real user conditions.

Talk to an Expert

Real-World Use Cases & amp; Examples of ‘ For Loop ’ in Robot Framework

For loops in Robot Framework are widely used to deal insistent validations, iterate through datasets, and execute the same action across multiple environments or input values. The examples below instance how loops solve real test problems across UI, API, and data-driven scenario.

Validating Multiple Form Fields

When a page contains several remark fields, a eyelet allows validating each field without duplicating steps.

* * * Test Cases * * * Validate Multiple Form Fields Open Browser https: //example.com/form chrome @ {battlefield} = Create List username netmail sound FOR $ {field} IN @ {fields} Element Should Be Visible id= $ {field} Element Should Be Enabled id= $ {field} END Close Browser

This 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 get cross-browser issues betimes.

* * * Test Cases * * * Cross Browser Test @ {browsers} = Create List chrome firefox edge FOR $ {browser} IN @ {browser} Open Browser https: //shop.com $ {browser} Page Should Contain Shop Now Close Browser END

Teams often use this figure with BrowserStack Automate to scale multi-browser examination.

Data-Driven API Testing

Testing multiple payloads becomes simple with a grummet.

* * * 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 END

This 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-bellied $ {schoolbook} END

This work good for dashboards, account, and admin venire.

Bulk Upload or Multi-Step Flows

If the test must upload multiple files or recur a workflow, a loop get the succession clean and reusable.

* * * Test Cases * * * Upload Multiple Files @ {files} = Create List file1.png file2.pdf file3.jpg FOR $ {file} IN @ {file} Choose File id=upload $ {CURDIR} / $ {file} Click Button id=submit Page Should Contain Upload Successful END

Great for regression tests involving multiple data samples.

Stress Testing with Range Loops

A FOR IN RANGEeyelet helps repeat an activity more times than manually virtual.

* * * Test Cases * * * Stress Test Login FOR $ {i} IN RANGE 1 20 Attempt Login With Invalid Credentials Page Should Contain Invalid username or password END

Utilitarian for negative testing and rate-limiting validations.

Read More:

Controlling the execution of a for loop manually

In Robot Framework, you can manually control the flow of a FOR grommet using built-in keywords. This allows you to influence when to skip specific iterations or exit the grommet early based on custom conditions.

Similar to traditional programming languages like Python, where shift and continue statements are used to negociate loop execution, Robot Framework provides tantamount keywords:

  • Exit For Loop If— Terminates the grummet early if a afford condition is met.
  • Continue For Loop If— Skips the current looping and takings to the future one if the condition is evaluated as true.

These keywords help optimize test suit by avoiding unnecessary stairs or looping, specially when specific criteria are already satisfied or invalid.

Example:

FOR $ {point} IN @ {list} $ {result} = Run Keyword And Return Status Should Be Equal $ {detail} foo Continue For Loop If $ {resolution} Log $ {item} Exit For Loop If ' $ {item} ' == 'bar' END

In this representative:

  • Continue For Loop If skips the current iteration if $ {particular} is equal to & # 8220; foo & # 8221;.
  • Exit For Loop If quit the loop solely if $ {item} touch & # 8220; bar & # 8221;.

Read More:

Common Issues and Troubleshooting the For Loop

Several common issues may arise while using FOR loop in Robot Framework, particularly if you ’ re new to it.

1. Incorrect Indentation

Robot Framework is indentation-sensitive. If the iteration body is not correctly indent under the FOR keyword, the loop may not fulfill as expected or could throw an error.

Fix:Ensure all keywords inside the grommet are consistently indented and adjust under the FOR block.

2. Missing END Statement (Robot Framework 4.0+)

From Robot Framework 4.0 onwards, loops require an expressed END to indicate the end of the eyelet body.

Fix:Always add an END statement after the concluding keyword in the loop.

3. Improper List or Variable Usage

Trying to ingeminate over an undefined or improperly formatted tilt can cause the loop to fail.

Fix: Ensure the tilt is defined correctly and initialized before the iteration. Use @ {list} syntax for tilt.

4. Incorrect Loop Syntax

Using outdated or mixed syntax (such as forgetting IN, or lose variable) can lead to execution errors.

Fix:Use the right format:

FOR $ {item} IN @ {tilt} Log $ {particular} END

5. 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 release.

Fix:Double-check the conditions used in the Exit For Loop If to see they trigger when expected.

6. Data Type Mismatches

Comparisons in loop weather can fail silently if the datum types are inconsistent, such as equate a number to a string.

Fix: Ensure that the values being compared are of compatible character. Use type conversion if needed.

Best Practices for Using For Loops in Robot Framework

Follow these best practices when using for cringle in Robot Framework to enhance your exam case.

  • Keep it simple: The most effective use of for loops is when the iteration logic is simple and easy to understand. Complex or pervert iteration logic can create your code harder to read and debug.
  • Use descriptive variable names: Use variable name that clearly describe what the variable represents. This can make our code more readable and help prevent mistake.
  • Limit the scope of variables: It & # 8217; s generally a full idea to limit the compass of variable used in for loops to the loop itself. This can help prevent naming conflicts and make our code easier to understand.
  • Avoid alter the lean during iteration: Modifying the list be iterate over during the loop can lead to unexpected behavior and errors. If we need to modify the list, deal creating a copy before iterating.
  • Use the range () function for iterating over indicator: When restate over a list and demand the index of each item, use the orbit () function. This allows us to retell over the indices of the lean rather of the values themselves.
  • Use built-in keywords whenever possible: Robot Framework provides several built-in keywords for ingeminate over lists and dictionaries. Whenever possible, use these keywords alternatively of enforce your looping logic.
  • Test thoroughly: As with any codification, it & # 8217; s significant to test our for loops thoroughly to ensure they are working as ask. Test cases should include edge and negative scenario to secure your code is robust and error-free.
 Also Read:

Loops vs. User-Defined Keywords in Robot Framework

Loopsin Robot Framework are utilise when test steps need to be repeated for multiple inputs, datasets, or environments. They are ideal for ingeminate through lists, ranges, or paired values and help eliminate double the like keyword episode multiple multiplication. Loops shine in data-driven scenarios—validating form fields, checking multiple API payloads, or escape the like UI interactions across different browser.

User-defined keywords, on the former hand, are best suited for group related steps into a reusable unit. They help organize test cases, reduce welter, and maintain logic in one place instead of repeating long succession. Keywords make the test suite more readable and allow central updates: change one keyword update every test that uses it.

In drill, iteration and user-defined keywords employment better together. A loop handles iteration, while the repeated steps inside it are package into a clean, reclaimable keyword. This approach keep tests scalable, easygoing to maintain, and far less error-prone.

Loops vs. User-Defined Keywords in Robot Framework

AspectLoopsUser-Defined Keywords
PurposeRepeat a set of steps for multiple items or iterationsGroup related step into reusable, maintainable keywords
Best Use CaseData-driven testing, iterating over lean, ranges, or paired valuesOrganizing workflows, trim duplicate, improving readability
When to ChooseWhen the same action must run multiple times with different inputWhen steps organize a ordered unit that appears in multiple examination
AdvantagesEliminates repetitive blocks, supports dynamic input processingCentralized logic, cleaner test cases, easygoing update
LimitationsCan become hard to read if loops grow composite or nestedNot ideal for large sets of insistent activeness without eyelet
Typical PatternLoop iterates → keywords execute inside each iterationKeyword encapsulates logic → can be called inwardly loops
Ideal TogetherRun intertwine for iteration across datasetsUse keywords to keep grummet contented clean and recyclable

Read More:

Conclusion

For loops in Robot Framework assistance automatize insistent actions by let you to ingeminate over lists, lexicon, or early sequences without duplicating code. Instead of publish the same set of steps multiple times, you can use a grommet to execute them dynamically for each input. This reduces redundance, meliorate readability, and makes test cases easygoing to update and scale.

Run your Robot Framework tests on real browsers and devices utilise to validate them under real-world conditions. With support for parallel execution, integration, and debugging tools like video logs and screenshots, BrowserStack enables fast, more exact testing at scale.

Tags

FAQs

A for loop in Robot Framework is a control structure that allows repeating a set of keywords for each item in a leaning, dictionary, range, or paired dataset. It helps reduce duplicate steps and do tests more maintainable.

A canonical iteration use theFOR … IN syntax. You define a list of values and execute the same keywords for each item. Proper indentation andENDare required to distinguish the eyelet boundary.

FOR IN iterates through items in a list, whileFOR IN RANGEgenerates a successiveness of numbers for a fixed number of repetitions. RANGE loops are useful for accent tests or index-based operations.

Yes. Robot Framework providesFOR IN ZIP, which iterate through two or more lists in parallel, pairing ingredient by position. This is helpful for input–output validation or form-field mapping.

Use FOR IN ENUMERATEwhen you need both the value and its index. It is useful for table establishment, row-level assertions, and debugging inclination positions during tryout performance.

Yes. Nested loops allow multi-level looping, such as validating multi-dimensional datasets or running the like checks across combination of examination stimulus. However, they should be managed carefully to sustain readability.

Robot Framework does not have a built-inbreak, but you can check execution apply inlineIFconditions and keywords likeExit For Loop If(usable in new versions) to stop or cut loop.

Common issue include incorrect indent, missingEND, wrong variable types, or passing an empty list. Validating data before the loop starts facilitate avoid silent failures.

Yes. Loops inside user keywords are mutual for creating reusable validation logic, input processors, or structured workflows. This keeps test cases clean and concise.

63,000+ Views

# Ask-and-Contributeabout this theme with our Discord community.

Related Guides

Automate This With SUSA

Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts needed.

Try SUSA Free

Test Your App Autonomously

Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts.

Try SUSA Free