HOME

TheInfoList



OR:

In computer programming, foreach loop (or for each loop) is a control flow statement for traversing items in a collection. is usually used in place of a standard loop statement. Unlike other loop constructs, however, loops usually maintain no explicit counter: they essentially say "do this to everything in this set", rather than "do this times". This avoids potential
off-by-one error An off-by-one error or off-by-one bug (known by acronyms OBOE, OBO, OB1 and OBOB) is a logic error involving the discrete equivalent of a boundary condition. It often occurs in computer programming when an iterative loop iterates one time too m ...
s and makes code simpler to read. In
object-oriented Object-oriented programming (OOP) is a programming paradigm based on the concept of " objects", which can contain data and code. The data is in the form of fields (often known as attributes or ''properties''), and the code is in the form of p ...
languages, an
iterator In computer programming, an iterator is an object that enables a programmer to traverse a container, particularly lists. Various types of iterators are often provided via a container's interface. Though the interface and semantics of a given iter ...
, even if implicit, is often used as the means of traversal. The statement in some languages has some defined order, processing each item in the collection from the first to the last. The statement in many other languages, especially array programming languages, does not have any particular order. This simplifies
loop optimization In compiler theory, loop optimization is the process of increasing execution speed and reducing the overheads associated with loops. It plays an important role in improving cache performance and making effective use of parallel processing capab ...
in general and in particular allows
vector processing In computing, a vector processor or array processor is a central processing unit (CPU) that implements an instruction set where its instructions are designed to operate efficiently and effectively on large one-dimensional arrays of data call ...
of items in the collection concurrently.


Syntax

Syntax varies among languages. Most use the simple word for, roughly as follows: for each item in collection: do something to item


Language support

Programming language A programming language is a system of notation for writing computer programs. Most programming languages are text-based formal languages, but they may also be graphical. They are a kind of computer language. The description of a programming ...
s which support foreach loops include
ABC ABC are the first three letters of the Latin script known as the alphabet. ABC or abc may also refer to: Arts, entertainment, and media Broadcasting * American Broadcasting Company, a commercial U.S. TV broadcaster ** Disney–ABC Television ...
, ActionScript, Ada, C++11, C#, ColdFusion Markup Language (CFML), Cobra, D,
Daplex Daplex is a computer language introduced in 1981 by David Shipman of the Computer Corporation of America. Daplex was designed for creating distributed database systems and can be used as a global query language Query languages, data query langua ...
(query language),
Delphi Delphi (; ), in legend previously called Pytho (Πυθώ), in ancient times was a sacred precinct that served as the seat of Pythia, the major oracle who was consulted about important decisions throughout the ancient classical world. The ora ...
,
ECMAScript ECMAScript (; ES) is a JavaScript standard intended to ensure the interoperability of web pages across different browsers. It is standardized by Ecma International in the documenECMA-262 ECMAScript is commonly used for client-side scripting o ...
, Erlang,
Java Java (; id, Jawa, ; jv, ꦗꦮ; su, ) is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea to the north. With a population of 151.6 million people, Java is the world's most ...
(since 1.5),
JavaScript JavaScript (), often abbreviated as JS, is a programming language that is one of the core technologies of the World Wide Web, alongside HTML and CSS. As of 2022, 98% of websites use JavaScript on the client side for webpage behavior, often ...
, Lua,
Objective-C Objective-C is a general-purpose, object-oriented programming language that adds Smalltalk-style messaging to the C programming language. Originally developed by Brad Cox and Tom Love in the early 1980s, it was selected by NeXT for its NeXTS ...
(since 2.0),
ParaSail Parasailing, also known as parascending, paraskiing or parakiting, is a recreational kiting activity where a person is towed behind a vehicle while attached to a specially designed canopy wing that resembles a parachute, known as a parasail w ...
,
Perl Perl is a family of two high-level, general-purpose, interpreted, dynamic programming languages. "Perl" refers to Perl 5, but from 2000 to 2019 it also referred to its redesigned "sister language", Perl 6, before the latter's name was offic ...
,
PHP PHP is a general-purpose scripting language geared toward web development. It was originally created by Danish-Canadian programmer Rasmus Lerdorf in 1993 and released in 1995. The PHP reference implementation is now produced by The PHP Group. ...
,
Prolog Prolog is a logic programming language associated with artificial intelligence and computational linguistics. Prolog has its roots in first-order logic, a formal logic, and unlike many other programming languages, Prolog is intended primarily ...
,
Python Python may refer to: Snakes * Pythonidae, a family of nonvenomous snakes found in Africa, Asia, and Australia ** ''Python'' (genus), a genus of Pythonidae found in Africa and Asia * Python (mythology), a mythical serpent Computing * Python (pr ...
, R,
REALbasic The Xojo programming environment and programming language is developed and commercially marketed by Xojo, Inc. of Austin, Texas for software development targeting macOS, Microsoft Windows, Linux, iOS, the Web and Raspberry Pi. Xojo uses a p ...
, Rebol,
Red Red is the color at the long wavelength end of the visible spectrum of light, next to orange and opposite violet. It has a dominant wavelength of approximately 625–740 nanometres. It is a primary color in the RGB color model and a secondary ...
,
Ruby A ruby is a pinkish red to blood-red colored gemstone, a variety of the mineral corundum ( aluminium oxide). Ruby is one of the most popular traditional jewelry gems and is very durable. Other varieties of gem-quality corundum are called sap ...
, Scala,
Smalltalk Smalltalk is an object-oriented, dynamically typed reflective programming language. It was designed and created in part for educational use, specifically for constructionist learning, at the Learning Research Group (LRG) of Xerox PARC by Alan K ...
,
Swift Swift or SWIFT most commonly refers to: * SWIFT, an international organization facilitating transactions between banks ** SWIFT code * Swift (programming language) * Swift (bird), a family of birds It may also refer to: Organizations * SWIFT ...
, Tcl,
tcsh tcsh ( “tee-see-shell”, “tee-shell”, or as “tee see ess aitch”, tcsh) is a Unix shell based on and backward compatible with the C shell (csh). Shell It is essentially the C shell with programmable command-line completion, command-l ...
,
Unix shell A Unix shell is a command-line interpreter or shell that provides a command line user interface for Unix-like operating systems. The shell is both an interactive command language and a scripting language, and is used by the operating system to ...
s,
Visual Basic .NET Visual Basic, originally called Visual Basic .NET (VB.NET), is a multi-paradigm, object-oriented programming language, implemented on .NET, Mono, and the .NET Framework. Microsoft launched VB.NET in 2002 as the successor to its original Vi ...
, and
Windows PowerShell PowerShell is a task automation and configuration management program from Microsoft, consisting of a command-line shell and the associated scripting language. Initially a Windows component only, known as Windows PowerShell, it was made open-sourc ...
. Notable languages without foreach are C, and C++ pre-C++11.


ActionScript 3.0

ActionScript supports the ECMAScript 4.0 Standard for for each .. in which pulls the value at each index. var foo:Object = ; for each (var value:int in foo) // returns "1" then "2" It also supports for .. in which pulls the key at each index. for (var key:String in foo) // returns "apple" then "orange"


Ada

Ada supports foreach loops as part of the normal
for loop In computer science a for-loop or for loop is a control flow statement for specifying iteration. Specifically, a for loop functions by running a section of code repeatedly until a certain condition has been satisfied. For-loops have two part ...
. Say X is an array: for I in X'Range loop X (I) := Get_Next_Element; end loop; This syntax is used on mostly arrays, but will also work with other types when a full iteration is needed. Ada 2012 has generalized loops to foreach loops on any kind of container (array, lists, maps...): for Obj of X loop -- Work on Obj end loop;


C

The C language does not have collections or a foreach construct. However, it has several standard data structures that can be used as collections, and foreach can be made easily with a macro. However, two obvious problems occur: * The macro is unhygienic: it declares a new variable in the existing scope which remains after the loop. * One foreach macro cannot be defined that works with different collection types (e.g., array and linked list) or that is extensible to user types. C string as a collection of char #include /* foreach macro viewing a string as a collection of char values */ #define foreach(ptrvar, strvar) \ char* ptrvar; \ for (ptrvar = strvar; (*ptrvar) != '\0'; *ptrvar++) int main(int argc, char** argv) C int array as a collection of int (array size known at compile-time) #include /* foreach macro viewing an array of int values as a collection of int values */ #define foreach(intpvar, intarr) \ int* intpvar; \ for (intpvar = intarr; intpvar < (intarr + (sizeof(intarr)/sizeof(intarr )); ++intpvar) int main(int argc, char** argv) Most general: string or array as collection (collection size known at run-time) : ''Note: can be removed and
typeof typeof, alternately also typeOf, and TypeOf, is an operator provided by several programming languages to determine the data type of a variable. This is useful when constructing programs that must accept multiple types of data without explicitly s ...
(col
used in its place with GCC'' #include #include /* foreach macro viewing an array of given type as a collection of values of given type */ #define arraylen(arr) (sizeof(arr)/sizeof(arr ) #define foreach(idxtype, idxpvar, col, colsiz) \ idxtype* idxpvar; \ for (idxpvar = col; idxpvar < (col + colsiz); ++idxpvar) int main(int argc, char** argv)


C#

In C#, assuming that myArray is an array of integers: foreach (int x in myArray)
Language Integrated Query Language Integrated Query (LINQ, pronounced "link") is a Microsoft .NET Framework component that adds native data querying capabilities to .NET languages, originally released as a major part of .NET Framework 3.5 in 2007. LINQ extends the langu ...
(LINQ) provides the following syntax, accepting a delegate or lambda expression: myArray.ToList().ForEach(x => Console.WriteLine(x));


C++

C++11 provides a foreach loop. The syntax is similar to that of
Java Java (; id, Jawa, ; jv, ꦗꦮ; su, ) is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea to the north. With a population of 151.6 million people, Java is the world's most ...
: #include int main() C++11 range-based for statements have been implemented in
GNU Compiler Collection The GNU Compiler Collection (GCC) is an optimizing compiler produced by the GNU Project supporting various programming languages, hardware architectures and operating systems. The Free Software Foundation (FSF) distributes GCC as free softwa ...
(GCC) (since version 4.6),
Clang Clang is a compiler front end for the C, C++, Objective-C, and Objective-C++ programming languages, as well as the OpenMP, OpenCL, RenderScript, CUDA, and HIP frameworks. It acts as a drop-in replacement for the GNU Compiler Collection (GCC) ...
(since version 3.0) and
Visual C++ Microsoft Visual C++ (MSVC) is a compiler for the C, C++ and C++/CX programming languages by Microsoft. MSVC is proprietary software; it was originally a standalone product but later became a part of Visual Studio and made available in both tr ...
2012 (version 11 ) The range-based for is
syntactic sugar In computer science, syntactic sugar is syntax within a programming language that is designed to make things easier to read or to express. It makes the language "sweeter" for human use: things can be expressed more clearly, more concisely, or in ...
equivalent to: for (auto __anon = begin(myint); __anon != end(myint); ++__anon) The compiler uses argument-dependent lookup to resolve the begin and end functions. The C++ Standard Library also supports for_each, that applies each element to a function, which can be any predefined function or a lambda expression. While range-based for is only from the beginning to the end, the range and direction you can change the direction or range by altering the first two parameters. #include #include // contains std::for_each #include int main() Qt, a C++ framework, offers a macro providing foreach loops using the STL iterator interface: #include #include int main()
Boost Boost, boosted or boosting may refer to: Science, technology and mathematics * Boost, positive manifold pressure in turbocharged engines * Boost (C++ libraries), a set of free peer-reviewed portable C++ libraries * Boost (material), a material b ...
, a set of free peer-reviewed portable C++ libraries also provides foreach loops: #include #include int main()


C++/CLI

The C++/CLI language proposes a construct similar to C#. Assuming that myArray is an array of integers: for each (int x in myArray)


ColdFusion Markup Language (CFML)


Script syntax

// arrays arrayeach( ,2,3,4,5 function(v)); // or for (v in ,2,3,4,5 // or // (Railo only; not supported in ColdFusion) letters = a","b","c","d","e" letters.each(function(v)); // structs for (k in collection) // or structEach(collection, function(k,v)); // or // (Railo only; not supported in ColdFusion) collection.each(function(k,v));


Tag syntax

a','b','c','d','e'"> #v# CFML incorrectly identifies the value as "index" in this construct; the index variable does receive the actual value of the array element, not its index. #collection


Common Lisp

Common Lisp provides foreach ability either with the ''dolist'' macro: (dolist (i '(1 3 5 6 8 10 14 17)) (print i)) or the powerful ''loop'' macro to iterate on more data types (loop for i in '(1 3 5 6 8 10 14 17) do (print i)) and even with the ''mapcar'' function: (mapcar #'print '(1 3 5 6 8 10 14 17))


D

foreach(item; set) or foreach(argument)


Dart

for (final element in someCollection)


Object Pascal, Delphi

Foreach support was added in
Delphi Delphi (; ), in legend previously called Pytho (Πυθώ), in ancient times was a sacred precinct that served as the seat of Pythia, the major oracle who was consulted about important decisions throughout the ancient classical world. The ora ...
2005, and uses an enumerator variable that must be declared in the ''var'' section. for enumerator in collection do begin //do something here end;


Eiffel

The iteration (foreach) form of the
Eiffel Eiffel may refer to: Places * Eiffel Peak, a summit in Alberta, Canada * Champ de Mars – Tour Eiffel station, Paris, France; a transit station Structures * Eiffel Tower, in Paris, France, designed by Gustave Eiffel * Eiffel Bridge, Ungheni, ...
loop construct is introduced by the keyword across. In this example, every element of the structure my_list is printed: across my_list as ic loop print (ic.item) end The local entity ic is an instance of the library class ITERATION_CURSOR. The cursor's feature item provides access to each structure element. Descendants of class ITERATION_CURSOR can be created to handle specialized iteration algorithms. The types of objects that can be iterated across (my_list in the example) are based on classes that inherit from the library class ITERABLE. The iteration form of the Eiffel loop can also be used as a boolean expression when the keyword loop is replaced by either all (effecting
universal quantification In mathematical logic, a universal quantification is a type of quantifier, a logical constant which is interpreted as "given any" or "for all". It expresses that a predicate can be satisfied by every member of a domain of discourse. In other ...
) or some (effecting
existential quantification In predicate logic, an existential quantification is a type of quantifier, a logical constant which is interpreted as "there exists", "there is at least one", or "for some". It is usually denoted by the logical operator symbol ∃, which, whe ...
). This iteration is a boolean expression which is true if all items in my_list have counts greater than three: across my_list as ic all ic.item.count > 3 end The following is true if at least one item has a count greater than three: across my_list as ic some ic.item.count > 3 end


Go

Go's foreach loop can be used to loop over an array, slice, string, map, or channel. Using the two-value form, we get the index/key (first element) and the value (second element): for index, value := range someCollection Using the one-value form, we get the index/key (first element): for index := range someCollection


Groovy

Groovy ''Groovy'' (or, less commonly, ''groovie'' or ''groovey'') is a slang colloquialism popular during the 1950s, '60s and '70s. It is roughly synonymous with words such as "excellent", "fashionable", or "amazing", depending on context. History The ...
supports ''for'' loops over collections like arrays, lists and ranges: def x = ,2,3,4for (v in x) // loop over the 4-element array x for (v in ,2,3,4 // loop over 4-element literal list for (v in 1..4) // loop over the range 1..4 Groovy also supports a C-style for loop with an array index: for (i = 0; i < x.size(); i++) Collections in Groovy can also be iterated over using the ''each'' keyword and a closure. By default, the loop dummy is named ''it'' x.each // print every element of the x array x.each // equivalent to line above, only loop dummy explicitly named "i"


Haskell

Haskell Haskell () is a general-purpose, statically-typed, purely functional programming language with type inference and lazy evaluation. Designed for teaching, research and industrial applications, Haskell has pioneered a number of programming lang ...
allows looping over lists with monadic actions using mapM_ and forM_ (mapM_ with its arguments flipped) fro
Control.Monad
It's also possible to generalize those functions to work on applicative functors rather than monads and any data structure that is traversable using traverse (for with its arguments flipped) and mapM (forM with its arguments flipped) fro


Haxe

for (value in iterable) Lambda.iter(iterable, function(value) trace(value));


Java

In
Java Java (; id, Jawa, ; jv, ꦗꦮ; su, ) is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea to the north. With a population of 151.6 million people, Java is the world's most ...
, a foreach-construct was introduced in
Java Development Kit The Java Development Kit (JDK) is a distribution of Java Technology by Oracle Corporation. It implements the Java Language Specification (JLS) and the Java Virtual Machine Specification (JVMS) and provides the Standard Edition (SE) of the Java ...
(JDK) 1.5.0. "Enhanced for Loop - This new language construct .. Official sources use several names for the construct. It is referred to as the "Enhanced for Loop", the "For-Each Loop", and the "foreach statement". for (Type item : iterableCollection) Java also provides the stream api since java 8: List intList = List.of(1, 2, 3, 4); intList.stream().forEach(i -> System.out.println(i));


JavaScript

The
ECMAScript 6 ECMAScript (; ES) is a JavaScript standard intended to ensure the interoperability of web pages across different browsers. It is standardized by Ecma International in the documenECMA-262 ECMAScript is commonly used for client-side scripting o ...
standard has for..of
/code> for index-less iteration over generators, arrays and more: for (var item of array) Alternatively, function-based style: array.forEach(item => ) For unordered iteration over the keys in an Object,
JavaScript JavaScript (), often abbreviated as JS, is a programming language that is one of the core technologies of the World Wide Web, alongside HTML and CSS. As of 2022, 98% of websites use JavaScript on the client side for webpage behavior, often ...
features the for...in loop: for (var key in object) To limit the iteration to the object's own properties, excluding those inherited through the prototype chain, it is sometimes useful to add a hasOwnProperty() test, if supported by the JavaScript engine (for WebKit/Safari, this means "in version 3 or later"). for (var key in object) ECMAScript 5 provided Object.keys method, to transfer the own keys of an object into array. var book = ; for(var key of Object.keys(book))


Lua

Iterate only through numerical index values: for index, value in ipairs(array) do -- do something end Iterate through all index values: for index, value in pairs(array) do -- do something end


Mathematica

In
Mathematica Wolfram Mathematica is a software system with built-in libraries for several areas of technical computing that allow machine learning, statistics, symbolic computation, data manipulation, network analysis, time series analysis, NLP, optimiza ...
, Do will simply evaluate an expression for each element of a list, without returning any value. In[]:= Do[doSomethingWithItem, ] It is more common to use Table, which returns the result of each evaluation in a new list. In[]:= list = ; In[]:= Table[item^2, ] Out[]=


MATLAB

for item = array %do something end


Mint

For each loops are supported in Mint, possessing the following syntax: for each element of list /* 'Do something.' */ end The for (;;) or while (true)
infinite loop In computer programming, an infinite loop (or endless loop) is a sequence of instructions that, as written, will continue endlessly, unless an external intervention occurs ("pull the plug"). It may be intentional. Overview This differs from: * ...
in Mint can be written using a for each loop and an infinitely long list. import type /* 'This function is mapped to' * 'each index number i of the' * 'infinitely long list.' */ sub identity(x) return x end /* 'The following creates the list' * ' , 1, 2, 3, 4, 5, ..., infinity */ infiniteList = list(identity) for each element of infiniteList /* 'Do something forever.' */ end


Objective-C

Foreach loops, called Fast enumeration, are supported starting in
Objective-C Objective-C is a general-purpose, object-oriented programming language that adds Smalltalk-style messaging to the C programming language. Originally developed by Brad Cox and Tom Love in the early 1980s, it was selected by NeXT for its NeXTS ...
2.0. They can be used to iterate over any object that implements the NSFastEnumeration protocol, including NSArray, NSDictionary (iterates over keys), NSSet, etc. NSArray *a = SArray new // Any container class can be substituted for(id obj in a) NSArrays can also broadcast a message to their members: NSArray *a = SArray new makeObjectsPerformSelector:@selector(printDescription) Where blocks are available, an NSArray can automatically perform a block on every contained item: yArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) The type of collection being iterated will dictate the item returned with each iteration. For example: NSDictionary *d = SDictionary new for(id key in d)


OCaml

OCaml OCaml ( , formerly Objective Caml) is a general-purpose, multi-paradigm programming language which extends the Caml dialect of ML with object-oriented features. OCaml was created in 1996 by Xavier Leroy, Jérôme Vouillon, Damien Doligez, Di ...
is a
functional language In computer science, functional programming is a programming paradigm where programs are constructed by applying and composing functions. It is a declarative programming paradigm in which function definitions are trees of expressions that ...
. Thus, the equivalent of a foreach loop can be achieved as a library function over lists and arrays. For lists: List.iter (fun x -> print_int x) ;2;3;4; or in short way: List.iter print_int ;2;3;4; For arrays: Array.iter (fun x -> print_int x) Array.iter_print_int_ 1;2;3;4, ;


__ParaSail_

The_ParaSail_ Parasailing,_also_known_as_parascending,_paraskiing_or_parakiting,_is_a_recreational__kiting_activity_where_a_person_is_towed_behind_a_vehicle_while_attached_to_a_specially_designed_canopy_wing_that_resembles_a_parachute,_known_as_a_parasail_w_...
_parallel_programming_language_supports_several_kinds_of_iterators,_including_a_general_"for_each"_iterator_over_a_container: var_Con_:_Container_:=_... //_... for_each_Elem_of_Con_concurrent_loop__//_loop_may_also_be_"forward"_or_"reverse"_or_unordered_(the_default) __//_..._do_something_with_Elem end_loop ParaSail_also_supports_filters_on_iterators,_and_the_ability_to_refer_to_both_the_key_and_the_value_of_a_map._Here_is_a_forward_iteration_over_the_elements_of_"My_Map"_selecting_only_elements_where_the_keys_are_in_"My_Set": var_My_Map_:_Map_Univ_String,_Value_Type_=>_Tree>_:=_... const_My_Set_:_Set_:=_ abc",_"def",_"ghi" for_each_ tr_=>_Trof_My_Map__forward_loop ___//_..._do_something_with_Str_or_Tr end_loop


__Pascal_

In_ Pascal,_ISO_standard_10206:1990_introduced_iteration_over_ set_types,_thus: var __elt:_ElementType; __eltset:_set_of_ElementType; for_elt_in_eltset_do __


__Perl_

In_Perl_ Perl_is_a_family_of_two__high-level,__general-purpose,__interpreted,_dynamic_programming_languages._"Perl"_refers_to_Perl_5,_but_from_2000_to_2019_it_also_referred_to_its_redesigned_"sister_language",_Perl_6,_before_the_latter's_name_was_offic_...
,_''foreach''_(which_is_equivalent_to_the_shorter_for)_can_be_used_to_traverse_elements_of_a_list.__The_expression_which_denotes_the_collection_to_loop_over_is_evaluated_in_list-context_and_each_item_of_the_resulting_list_is,_in_turn,_aliased_to_the_loop_variable. List_literal_example: foreach_(1,_2,_3,_4)_ Array_examples: foreach_(@arr)_ foreach_$x_(@arr)__ Hash_example: foreach_$x_(keys_%hash)_ Direct_modification_of_collection_members: @arr_=_(_'remove-foo',_'remove-bar'_); foreach_$x_(@arr) #_Now_@arr_=_('foo',_'bar');


__PHP_

foreach_($set_as_$value)_ It_is_also_possible_to_extract_both_keys_and_values_using_the_alternate_syntax: foreach_($set_as_$key_=>_$value)_ Direct_modification_of_collection_members: $arr_=_array(1,_2,_3); foreach_($arr_as_&$value)_ //_Now_$arr_=_array(2,_3,_4); //_also_works_with_the_full_syntax foreach_($arr_as_$key_=>_&$value)_
More_information


__Python_

for_item_in_iterable_collection: ____#_Do_something_with_item Python's_tuple_assignment,_fully_available_in_its_foreach_loop,_also_makes_it_trivial_to_iterate_on_(key,_value)_pairs_in_
associative_array In computer science, an associative array, map, symbol table, or dictionary is an abstract data type that stores a collection of (key, value) pairs, such that each possible key appears at most once in the collection. In mathematical terms an a ...
s: for_key,_value_in_some_dict.items():__#_Direct_iteration_on_a_dict_iterates_on_its_keys ____#_Do_stuff As_for_..._in_is_the_only_kind_of_for_loop_in_Python,_the_equivalent_to_the_"counter"_loop_found_in_other_languages_is... for_i_in_range(len(seq)): ____#_Do_something_to_seq ..._though_using_the_enumerate_function_is_considered_more_"Pythonic": for_i,_item_in_enumerate(seq): ____#_Do_stuff_with_item ____#_Possibly_assign_it_back_to_seq


__R_

for_(item_in_object)_ As_for_..._in_is_the_only_kind_of_for_loop_in_R,_the_equivalent_to_the_"counter"_loop_found_in_other_languages_is... for_(i_in_seq_along(object))_


__Racket_

(for_( tem_set __(do-something-with_item)) or_using_the_conventional_Scheme_for-each_function: (for-each_do-something-with_a-list) do-something-with_is_a_one-argument_function.


__Raku_

In_ Raku,_a_sister_language_to_Perl,_''for''_must_be_used_to_traverse_elements_of_a_list_(''foreach''_is_not_allowed)._The_expression_which_denotes_the_collection_to_loop_over_is_evaluated_in_list-context,_but_not_flattened_by_default,_and_each_item_of_the_resulting_list_is,_in_turn,_aliased_to_the_loop_variable(s). List_literal_example: for_1..4_ Array_examples: for_@arr_ The_for_loop_in_its_statement_modifier_form: .say_for_@arr; for_@arr_->_$x__ for_@arr_->_$x,_$y__ Hash_example: for_keys_%hash_->_$key_ or for_%hash.kv_->_$key,_$value_ or for_%hash_->_$x_ Direct_modification_of_collection_members_with_a_doubly_pointy_block,_''<->'':_ my_@arr_=_1,2,3; for_@arr_<->_$x_ #_Now_@arr_=_2,4,6;


__Ruby_

set.each_do_, item, __#_do_something_to_item end or for_item_in_set __#_do_something_to_item end This_can_also_be_used_with_a_hash. set.each_do_, item,value, __#_do_something_to_item __#_do_something_to_value end


__Rust_

The_for_loop_has_the_structure_for__in__._It_implicitly_calls_th
IntoIterator::into_iter
method_on_the_expression,_and_uses_the_resulting_value,_which_must_implement_th

trait._If_the_expression_is_itself_an_iterator,_it_is_used_directly_by_the_for_loop_through_a

that_returns_the_iterator_unchanged._The_loop_calls_the_Iterator::next_method_on_the_iterator_before_executing_the_loop_body._If_Iterator::next_returns_ Some(_),_the_value_inside_is_assigned_to_the_
pattern A pattern is a regularity in the world, in human-made design, or in abstract ideas. As such, the elements of a pattern repeat in a predictable manner. A geometric pattern is a kind of pattern formed of geometric shapes and typically repeated l ...
_and_the_loop_body_is_executed;_if_it_returns_None,_the_loop_is_terminated. let_mut_numbers_=_vec!
,_2,_3 The comma is a punctuation mark that appears in several variants in different languages. It has the same shape as an apostrophe or single closing quotation mark () in many typefaces, but it differs from them in being placed on the baseline o ...
//_Immutable_reference: for_number_in_&numbers_ for_square_in_numbers.iter().map(, x, _x_*_x)_ //_Mutable_reference: for_number_in_&mut_numbers_ //_prints_" ,_4,_6: println!("",_numbers); //_Consumes_the_Vec_and_creates_an_Iterator: for_number_in_numbers_ //_Errors_with_"borrow_of_moved_value": //_println!("",_numbers);


__Scala_

//_return_list_of_modified_elements items_map_ items_map_multiplyByTwo for__yield_doSomething(x) for__yield_multiplyByTwo(x) //_return_nothing,_just_perform_action items_foreach_ items_foreach_println for__doSomething(x) for__println(x) //_pattern_matching_example_in_for-comprehension for_((key,_value)_<-_someMap)_println(s"$key_->_$value")


__Scheme_

(for-each_do-something-with_a-list) do-something-with_is_a_one-argument_function.


__Smalltalk_

collection_do:_ _"do_something_to_item"_


__Swift_

Swift_ Swift_or_SWIFT_most_commonly_refers_to: *__SWIFT,_an_international_organization_facilitating_transactions_between_banks **__SWIFT_code_ *_Swift_(programming_language) *_Swift_(bird),_a_family_of_birds It_may_also_refer_to: _Organizations *__SWIFT_...
_uses_the_forin_construct_to_iterate_over_members_of_a_collection. for_thing_in_someCollection_ The_forin_loop_is_often_used_with_the_closed_and_half-open_range_constructs_to_iterate_over_the_loop_body_a_certain_number_of_times. for_i_in_0..<10_ for_i_in_0...10_


__SystemVerilog_

SystemVerilog SystemVerilog, standardized as IEEE 1800, is a hardware description and hardware verification language used to model, design, simulate, test and implement electronic systems. SystemVerilog is based on Verilog and some extensions, and since 20 ...
_supports_iteration_over_any_vector_or_array_type_of_any_dimensionality_using_the_foreach_keyword. A_trivial_example_iterates_over_an_array_of_integers: A_more_complex_example_iterates_over_an_associative_array_of_arrays_of_integers:


__Tcl_

_Tcl_uses_foreach_to_iterate_over_lists._It_is_possible_to_specify_more_than_one_iterator_variable,_in_which_case_they_are_assigned_sequential_values_from_the_list._ It_is_also_possible_to_iterate_over_more_than_one_list_simultaneously._In_the_following_i_assumes_sequential_values_of_the_first_list,_j_sequential_values_of_the_second_list:


__Visual_Basic_.NET_

For_Each_item_In_enumerable ____'_Do_something_with_item. Next or_without_
type_inference Type inference refers to the automatic detection of the type of an expression in a formal language. These include programming languages and mathematical type systems, but also natural languages in some branches of computer science and linguistic ...
For_Each_item_As_type_In_enumerable ____'_Do_something_with_item. Next


__Windows_


__Conventional_command_processor_

Invoke_a_hypothetical_frob_command_three_times,_giving_it_a_color_name_each_time. C:\>FOR_%%a_IN_(_red_green_blue_)_DO_frob_%%a


__Windows_PowerShell_

foreach_($item_in_$set)_ From_a_pipeline $list_, _ForEach-Object_ #_or_using_the_aliases $list_, _foreach_ $list_, _%_


__XSLT_

_ ___ _


__See_also_

*_
Do_while_loop In most computer programming languages a do while loop is a control flow statement that executes a block of code and then either repeats the block or exits the loop depending on a given boolean condition. The ''do while'' construct consists o ...
*_
For_loop In computer science a for-loop or for loop is a control flow statement for specifying iteration. Specifically, a for loop functions by running a section of code repeatedly until a certain condition has been satisfied. For-loops have two part ...
*_
While_loop In most computer programming languages, a while loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. The ''while'' loop can be thought of as a repeating if statement. Overview The '' ...
*_
Map_(higher-order_function) In many programming languages, map is the name of a higher-order function that applies a given function to each element of a collection, e.g. a list or set, returning the results in a collection of the same type. It is often called ''apply- ...


__References_

{{Reflist, 2 Articles_with_example_Ada_code Articles_with_example_Perl_code Articles_with_example_PHP_code Articles_with_example_Python_(programming_language)_code Articles_with_example_Racket_code Articles_with_example_Smalltalk_code Articles_with_example_Tcl_code Control_flow Programming_language_comparisons Articles_with_example_Java_code Articles_with_example_Haskell_code ru:Цикл_просмотраhtml" ;"title="1;2;3;4, ];; or in short way: Array.iter print_int 1;2;3;4, ;


ParaSail

The
ParaSail Parasailing, also known as parascending, paraskiing or parakiting, is a recreational kiting activity where a person is towed behind a vehicle while attached to a specially designed canopy wing that resembles a parachute, known as a parasail w ...
parallel programming language supports several kinds of iterators, including a general "for each" iterator over a container: var Con : Container := ... // ... for each Elem of Con concurrent loop // loop may also be "forward" or "reverse" or unordered (the default) // ... do something with Elem end loop ParaSail also supports filters on iterators, and the ability to refer to both the key and the value of a map. Here is a forward iteration over the elements of "My_Map" selecting only elements where the keys are in "My_Set": var My_Map : Map Univ_String, Value_Type => Tree> := ... const My_Set : Set := abc", "def", "ghi" for each tr => Trof My_Map forward loop // ... do something with Str or Tr end loop


Pascal

In Pascal, ISO standard 10206:1990 introduced iteration over set types, thus: var elt: ElementType; eltset: set of ElementType; for elt in eltset do


Perl

In
Perl Perl is a family of two high-level, general-purpose, interpreted, dynamic programming languages. "Perl" refers to Perl 5, but from 2000 to 2019 it also referred to its redesigned "sister language", Perl 6, before the latter's name was offic ...
, ''foreach'' (which is equivalent to the shorter for) can be used to traverse elements of a list. The expression which denotes the collection to loop over is evaluated in list-context and each item of the resulting list is, in turn, aliased to the loop variable. List literal example: foreach (1, 2, 3, 4) Array examples: foreach (@arr) foreach $x (@arr) Hash example: foreach $x (keys %hash) Direct modification of collection members: @arr = ( 'remove-foo', 'remove-bar' ); foreach $x (@arr) # Now @arr = ('foo', 'bar');


PHP

foreach ($set as $value) It is also possible to extract both keys and values using the alternate syntax: foreach ($set as $key => $value) Direct modification of collection members: $arr = array(1, 2, 3); foreach ($arr as &$value) // Now $arr = array(2, 3, 4); // also works with the full syntax foreach ($arr as $key => &$value)
More information


Python

for item in iterable_collection: # Do something with item Python's tuple assignment, fully available in its foreach loop, also makes it trivial to iterate on (key, value) pairs in
associative array In computer science, an associative array, map, symbol table, or dictionary is an abstract data type that stores a collection of (key, value) pairs, such that each possible key appears at most once in the collection. In mathematical terms an a ...
s: for key, value in some_dict.items(): # Direct iteration on a dict iterates on its keys # Do stuff As for ... in is the only kind of for loop in Python, the equivalent to the "counter" loop found in other languages is... for i in range(len(seq)): # Do something to seq ... though using the enumerate function is considered more "Pythonic": for i, item in enumerate(seq): # Do stuff with item # Possibly assign it back to seq


R

for (item in object) As for ... in is the only kind of for loop in R, the equivalent to the "counter" loop found in other languages is... for (i in seq_along(object))


Racket

(for ( tem set (do-something-with item)) or using the conventional Scheme for-each function: (for-each do-something-with a-list) do-something-with is a one-argument function.


Raku

In Raku, a sister language to Perl, ''for'' must be used to traverse elements of a list (''foreach'' is not allowed). The expression which denotes the collection to loop over is evaluated in list-context, but not flattened by default, and each item of the resulting list is, in turn, aliased to the loop variable(s). List literal example: for 1..4 Array examples: for @arr The for loop in its statement modifier form: .say for @arr; for @arr -> $x for @arr -> $x, $y Hash example: for keys %hash -> $key or for %hash.kv -> $key, $value or for %hash -> $x Direct modification of collection members with a doubly pointy block, ''<->'': my @arr = 1,2,3; for @arr <-> $x # Now @arr = 2,4,6;


Ruby

set.each do , item, # do something to item end or for item in set # do something to item end This can also be used with a hash. set.each do , item,value, # do something to item # do something to value end


Rust

The for loop has the structure for in . It implicitly calls th
IntoIterator::into_iter
method on the expression, and uses the resulting value, which must implement th

trait. If the expression is itself an iterator, it is used directly by the for loop through a

that returns the iterator unchanged. The loop calls the Iterator::next method on the iterator before executing the loop body. If Iterator::next returns Some(_), the value inside is assigned to the
pattern A pattern is a regularity in the world, in human-made design, or in abstract ideas. As such, the elements of a pattern repeat in a predictable manner. A geometric pattern is a kind of pattern formed of geometric shapes and typically repeated l ...
and the loop body is executed; if it returns None, the loop is terminated. let mut numbers = vec!
, 2, 3 The comma is a punctuation mark that appears in several variants in different languages. It has the same shape as an apostrophe or single closing quotation mark () in many typefaces, but it differs from them in being placed on the baseline o ...
// Immutable reference: for number in &numbers for square in numbers.iter().map(, x, x * x) // Mutable reference: for number in &mut numbers // prints " , 4, 6: println!("", numbers); // Consumes the Vec and creates an Iterator: for number in numbers // Errors with "borrow of moved value": // println!("", numbers);


Scala

// return list of modified elements items map items map multiplyByTwo for yield doSomething(x) for yield multiplyByTwo(x) // return nothing, just perform action items foreach items foreach println for doSomething(x) for println(x) // pattern matching example in for-comprehension for ((key, value) <- someMap) println(s"$key -> $value")


Scheme

(for-each do-something-with a-list) do-something-with is a one-argument function.


Smalltalk

collection do: "do something to item"


Swift

Swift Swift or SWIFT most commonly refers to: * SWIFT, an international organization facilitating transactions between banks ** SWIFT code * Swift (programming language) * Swift (bird), a family of birds It may also refer to: Organizations * SWIFT ...
uses the forin construct to iterate over members of a collection. for thing in someCollection The forin loop is often used with the closed and half-open range constructs to iterate over the loop body a certain number of times. for i in 0..<10 for i in 0...10


SystemVerilog

SystemVerilog SystemVerilog, standardized as IEEE 1800, is a hardware description and hardware verification language used to model, design, simulate, test and implement electronic systems. SystemVerilog is based on Verilog and some extensions, and since 20 ...
supports iteration over any vector or array type of any dimensionality using the foreach keyword. A trivial example iterates over an array of integers: A more complex example iterates over an associative array of arrays of integers:


Tcl

Tcl uses foreach to iterate over lists. It is possible to specify more than one iterator variable, in which case they are assigned sequential values from the list. It is also possible to iterate over more than one list simultaneously. In the following i assumes sequential values of the first list, j sequential values of the second list:


Visual Basic .NET

For Each item In enumerable ' Do something with item. Next or without
type inference Type inference refers to the automatic detection of the type of an expression in a formal language. These include programming languages and mathematical type systems, but also natural languages in some branches of computer science and linguistic ...
For Each item As type In enumerable ' Do something with item. Next


Windows


Conventional command processor

Invoke a hypothetical frob command three times, giving it a color name each time. C:\>FOR %%a IN ( red green blue ) DO frob %%a


Windows PowerShell

foreach ($item in $set) From a pipeline $list , ForEach-Object # or using the aliases $list , foreach $list , %


XSLT


See also

*
Do while loop In most computer programming languages a do while loop is a control flow statement that executes a block of code and then either repeats the block or exits the loop depending on a given boolean condition. The ''do while'' construct consists o ...
*
For loop In computer science a for-loop or for loop is a control flow statement for specifying iteration. Specifically, a for loop functions by running a section of code repeatedly until a certain condition has been satisfied. For-loops have two part ...
*
While loop In most computer programming languages, a while loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. The ''while'' loop can be thought of as a repeating if statement. Overview The '' ...
*
Map (higher-order function) In many programming languages, map is the name of a higher-order function that applies a given function to each element of a collection, e.g. a list or set, returning the results in a collection of the same type. It is often called ''apply- ...


References

{{Reflist, 2 Articles with example Ada code Articles with example Perl code Articles with example PHP code Articles with example Python (programming language) code Articles with example Racket code Articles with example Smalltalk code Articles with example Tcl code Control flow Programming language comparisons Articles with example Java code Articles with example Haskell code ru:Цикл просмотра>1;2;3;4, ; or in short way: Array.iter print_int Array.iter_print_int_ 1;2;3;4, ;


__ParaSail_

The_ParaSail_ Parasailing,_also_known_as_parascending,_paraskiing_or_parakiting,_is_a_recreational__kiting_activity_where_a_person_is_towed_behind_a_vehicle_while_attached_to_a_specially_designed_canopy_wing_that_resembles_a_parachute,_known_as_a_parasail_w_...
_parallel_programming_language_supports_several_kinds_of_iterators,_including_a_general_"for_each"_iterator_over_a_container: var_Con_:_Container_:=_... //_... for_each_Elem_of_Con_concurrent_loop__//_loop_may_also_be_"forward"_or_"reverse"_or_unordered_(the_default) __//_..._do_something_with_Elem end_loop ParaSail_also_supports_filters_on_iterators,_and_the_ability_to_refer_to_both_the_key_and_the_value_of_a_map._Here_is_a_forward_iteration_over_the_elements_of_"My_Map"_selecting_only_elements_where_the_keys_are_in_"My_Set": var_My_Map_:_Map_Univ_String,_Value_Type_=>_Tree>_:=_... const_My_Set_:_Set_:=_ abc",_"def",_"ghi" for_each_ tr_=>_Trof_My_Map__forward_loop ___//_..._do_something_with_Str_or_Tr end_loop


__Pascal_

In_ Pascal,_ISO_standard_10206:1990_introduced_iteration_over_ set_types,_thus: var __elt:_ElementType; __eltset:_set_of_ElementType; for_elt_in_eltset_do __


__Perl_

In_Perl_ Perl_is_a_family_of_two__high-level,__general-purpose,__interpreted,_dynamic_programming_languages._"Perl"_refers_to_Perl_5,_but_from_2000_to_2019_it_also_referred_to_its_redesigned_"sister_language",_Perl_6,_before_the_latter's_name_was_offic_...
,_''foreach''_(which_is_equivalent_to_the_shorter_for)_can_be_used_to_traverse_elements_of_a_list.__The_expression_which_denotes_the_collection_to_loop_over_is_evaluated_in_list-context_and_each_item_of_the_resulting_list_is,_in_turn,_aliased_to_the_loop_variable. List_literal_example: foreach_(1,_2,_3,_4)_ Array_examples: foreach_(@arr)_ foreach_$x_(@arr)__ Hash_example: foreach_$x_(keys_%hash)_ Direct_modification_of_collection_members: @arr_=_(_'remove-foo',_'remove-bar'_); foreach_$x_(@arr) #_Now_@arr_=_('foo',_'bar');


__PHP_

foreach_($set_as_$value)_ It_is_also_possible_to_extract_both_keys_and_values_using_the_alternate_syntax: foreach_($set_as_$key_=>_$value)_ Direct_modification_of_collection_members: $arr_=_array(1,_2,_3); foreach_($arr_as_&$value)_ //_Now_$arr_=_array(2,_3,_4); //_also_works_with_the_full_syntax foreach_($arr_as_$key_=>_&$value)_
More_information


__Python_

for_item_in_iterable_collection: ____#_Do_something_with_item Python's_tuple_assignment,_fully_available_in_its_foreach_loop,_also_makes_it_trivial_to_iterate_on_(key,_value)_pairs_in_
associative_array In computer science, an associative array, map, symbol table, or dictionary is an abstract data type that stores a collection of (key, value) pairs, such that each possible key appears at most once in the collection. In mathematical terms an a ...
s: for_key,_value_in_some_dict.items():__#_Direct_iteration_on_a_dict_iterates_on_its_keys ____#_Do_stuff As_for_..._in_is_the_only_kind_of_for_loop_in_Python,_the_equivalent_to_the_"counter"_loop_found_in_other_languages_is... for_i_in_range(len(seq)): ____#_Do_something_to_seq ..._though_using_the_enumerate_function_is_considered_more_"Pythonic": for_i,_item_in_enumerate(seq): ____#_Do_stuff_with_item ____#_Possibly_assign_it_back_to_seq


__R_

for_(item_in_object)_ As_for_..._in_is_the_only_kind_of_for_loop_in_R,_the_equivalent_to_the_"counter"_loop_found_in_other_languages_is... for_(i_in_seq_along(object))_


__Racket_

(for_( tem_set __(do-something-with_item)) or_using_the_conventional_Scheme_for-each_function: (for-each_do-something-with_a-list) do-something-with_is_a_one-argument_function.


__Raku_

In_ Raku,_a_sister_language_to_Perl,_''for''_must_be_used_to_traverse_elements_of_a_list_(''foreach''_is_not_allowed)._The_expression_which_denotes_the_collection_to_loop_over_is_evaluated_in_list-context,_but_not_flattened_by_default,_and_each_item_of_the_resulting_list_is,_in_turn,_aliased_to_the_loop_variable(s). List_literal_example: for_1..4_ Array_examples: for_@arr_ The_for_loop_in_its_statement_modifier_form: .say_for_@arr; for_@arr_->_$x__ for_@arr_->_$x,_$y__ Hash_example: for_keys_%hash_->_$key_ or for_%hash.kv_->_$key,_$value_ or for_%hash_->_$x_ Direct_modification_of_collection_members_with_a_doubly_pointy_block,_''<->'':_ my_@arr_=_1,2,3; for_@arr_<->_$x_ #_Now_@arr_=_2,4,6;


__Ruby_

set.each_do_, item, __#_do_something_to_item end or for_item_in_set __#_do_something_to_item end This_can_also_be_used_with_a_hash. set.each_do_, item,value, __#_do_something_to_item __#_do_something_to_value end


__Rust_

The_for_loop_has_the_structure_for__in__._It_implicitly_calls_th
IntoIterator::into_iter
method_on_the_expression,_and_uses_the_resulting_value,_which_must_implement_th

trait._If_the_expression_is_itself_an_iterator,_it_is_used_directly_by_the_for_loop_through_a

that_returns_the_iterator_unchanged._The_loop_calls_the_Iterator::next_method_on_the_iterator_before_executing_the_loop_body._If_Iterator::next_returns_ Some(_),_the_value_inside_is_assigned_to_the_
pattern A pattern is a regularity in the world, in human-made design, or in abstract ideas. As such, the elements of a pattern repeat in a predictable manner. A geometric pattern is a kind of pattern formed of geometric shapes and typically repeated l ...
_and_the_loop_body_is_executed;_if_it_returns_None,_the_loop_is_terminated. let_mut_numbers_=_vec!
,_2,_3 The comma is a punctuation mark that appears in several variants in different languages. It has the same shape as an apostrophe or single closing quotation mark () in many typefaces, but it differs from them in being placed on the baseline o ...
//_Immutable_reference: for_number_in_&numbers_ for_square_in_numbers.iter().map(, x, _x_*_x)_ //_Mutable_reference: for_number_in_&mut_numbers_ //_prints_" ,_4,_6: println!("",_numbers); //_Consumes_the_Vec_and_creates_an_Iterator: for_number_in_numbers_ //_Errors_with_"borrow_of_moved_value": //_println!("",_numbers);


__Scala_

//_return_list_of_modified_elements items_map_ items_map_multiplyByTwo for__yield_doSomething(x) for__yield_multiplyByTwo(x) //_return_nothing,_just_perform_action items_foreach_ items_foreach_println for__doSomething(x) for__println(x) //_pattern_matching_example_in_for-comprehension for_((key,_value)_<-_someMap)_println(s"$key_->_$value")


__Scheme_

(for-each_do-something-with_a-list) do-something-with_is_a_one-argument_function.


__Smalltalk_

collection_do:_ _"do_something_to_item"_


__Swift_

Swift_ Swift_or_SWIFT_most_commonly_refers_to: *__SWIFT,_an_international_organization_facilitating_transactions_between_banks **__SWIFT_code_ *_Swift_(programming_language) *_Swift_(bird),_a_family_of_birds It_may_also_refer_to: _Organizations *__SWIFT_...
_uses_the_forin_construct_to_iterate_over_members_of_a_collection. for_thing_in_someCollection_ The_forin_loop_is_often_used_with_the_closed_and_half-open_range_constructs_to_iterate_over_the_loop_body_a_certain_number_of_times. for_i_in_0..<10_ for_i_in_0...10_


__SystemVerilog_

SystemVerilog SystemVerilog, standardized as IEEE 1800, is a hardware description and hardware verification language used to model, design, simulate, test and implement electronic systems. SystemVerilog is based on Verilog and some extensions, and since 20 ...
_supports_iteration_over_any_vector_or_array_type_of_any_dimensionality_using_the_foreach_keyword. A_trivial_example_iterates_over_an_array_of_integers: A_more_complex_example_iterates_over_an_associative_array_of_arrays_of_integers:


__Tcl_

_Tcl_uses_foreach_to_iterate_over_lists._It_is_possible_to_specify_more_than_one_iterator_variable,_in_which_case_they_are_assigned_sequential_values_from_the_list._ It_is_also_possible_to_iterate_over_more_than_one_list_simultaneously._In_the_following_i_assumes_sequential_values_of_the_first_list,_j_sequential_values_of_the_second_list:


__Visual_Basic_.NET_

For_Each_item_In_enumerable ____'_Do_something_with_item. Next or_without_
type_inference Type inference refers to the automatic detection of the type of an expression in a formal language. These include programming languages and mathematical type systems, but also natural languages in some branches of computer science and linguistic ...
For_Each_item_As_type_In_enumerable ____'_Do_something_with_item. Next


__Windows_


__Conventional_command_processor_

Invoke_a_hypothetical_frob_command_three_times,_giving_it_a_color_name_each_time. C:\>FOR_%%a_IN_(_red_green_blue_)_DO_frob_%%a


__Windows_PowerShell_

foreach_($item_in_$set)_ From_a_pipeline $list_, _ForEach-Object_ #_or_using_the_aliases $list_, _foreach_ $list_, _%_


__XSLT_

_ ___ _


__See_also_

*_
Do_while_loop In most computer programming languages a do while loop is a control flow statement that executes a block of code and then either repeats the block or exits the loop depending on a given boolean condition. The ''do while'' construct consists o ...
*_
For_loop In computer science a for-loop or for loop is a control flow statement for specifying iteration. Specifically, a for loop functions by running a section of code repeatedly until a certain condition has been satisfied. For-loops have two part ...
*_
While_loop In most computer programming languages, a while loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. The ''while'' loop can be thought of as a repeating if statement. Overview The '' ...
*_
Map_(higher-order_function) In many programming languages, map is the name of a higher-order function that applies a given function to each element of a collection, e.g. a list or set, returning the results in a collection of the same type. It is often called ''apply- ...


__References_

{{Reflist, 2 Articles_with_example_Ada_code Articles_with_example_Perl_code Articles_with_example_PHP_code Articles_with_example_Python_(programming_language)_code Articles_with_example_Racket_code Articles_with_example_Smalltalk_code Articles_with_example_Tcl_code Control_flow Programming_language_comparisons Articles_with_example_Java_code Articles_with_example_Haskell_code ru:Цикл_просмотраhtml" ;"title="1;2;3;4, ];; or in short way: Array.iter print_int 1;2;3;4, ;


ParaSail

The
ParaSail Parasailing, also known as parascending, paraskiing or parakiting, is a recreational kiting activity where a person is towed behind a vehicle while attached to a specially designed canopy wing that resembles a parachute, known as a parasail w ...
parallel programming language supports several kinds of iterators, including a general "for each" iterator over a container: var Con : Container := ... // ... for each Elem of Con concurrent loop // loop may also be "forward" or "reverse" or unordered (the default) // ... do something with Elem end loop ParaSail also supports filters on iterators, and the ability to refer to both the key and the value of a map. Here is a forward iteration over the elements of "My_Map" selecting only elements where the keys are in "My_Set": var My_Map : Map Univ_String, Value_Type => Tree> := ... const My_Set : Set := abc", "def", "ghi" for each tr => Trof My_Map forward loop // ... do something with Str or Tr end loop


Pascal

In Pascal, ISO standard 10206:1990 introduced iteration over set types, thus: var elt: ElementType; eltset: set of ElementType; for elt in eltset do


Perl

In
Perl Perl is a family of two high-level, general-purpose, interpreted, dynamic programming languages. "Perl" refers to Perl 5, but from 2000 to 2019 it also referred to its redesigned "sister language", Perl 6, before the latter's name was offic ...
, ''foreach'' (which is equivalent to the shorter for) can be used to traverse elements of a list. The expression which denotes the collection to loop over is evaluated in list-context and each item of the resulting list is, in turn, aliased to the loop variable. List literal example: foreach (1, 2, 3, 4) Array examples: foreach (@arr) foreach $x (@arr) Hash example: foreach $x (keys %hash) Direct modification of collection members: @arr = ( 'remove-foo', 'remove-bar' ); foreach $x (@arr) # Now @arr = ('foo', 'bar');


PHP

foreach ($set as $value) It is also possible to extract both keys and values using the alternate syntax: foreach ($set as $key => $value) Direct modification of collection members: $arr = array(1, 2, 3); foreach ($arr as &$value) // Now $arr = array(2, 3, 4); // also works with the full syntax foreach ($arr as $key => &$value)
More information


Python

for item in iterable_collection: # Do something with item Python's tuple assignment, fully available in its foreach loop, also makes it trivial to iterate on (key, value) pairs in
associative array In computer science, an associative array, map, symbol table, or dictionary is an abstract data type that stores a collection of (key, value) pairs, such that each possible key appears at most once in the collection. In mathematical terms an a ...
s: for key, value in some_dict.items(): # Direct iteration on a dict iterates on its keys # Do stuff As for ... in is the only kind of for loop in Python, the equivalent to the "counter" loop found in other languages is... for i in range(len(seq)): # Do something to seq ... though using the enumerate function is considered more "Pythonic": for i, item in enumerate(seq): # Do stuff with item # Possibly assign it back to seq


R

for (item in object) As for ... in is the only kind of for loop in R, the equivalent to the "counter" loop found in other languages is... for (i in seq_along(object))


Racket

(for ( tem set (do-something-with item)) or using the conventional Scheme for-each function: (for-each do-something-with a-list) do-something-with is a one-argument function.


Raku

In Raku, a sister language to Perl, ''for'' must be used to traverse elements of a list (''foreach'' is not allowed). The expression which denotes the collection to loop over is evaluated in list-context, but not flattened by default, and each item of the resulting list is, in turn, aliased to the loop variable(s). List literal example: for 1..4 Array examples: for @arr The for loop in its statement modifier form: .say for @arr; for @arr -> $x for @arr -> $x, $y Hash example: for keys %hash -> $key or for %hash.kv -> $key, $value or for %hash -> $x Direct modification of collection members with a doubly pointy block, ''<->'': my @arr = 1,2,3; for @arr <-> $x # Now @arr = 2,4,6;


Ruby

set.each do , item, # do something to item end or for item in set # do something to item end This can also be used with a hash. set.each do , item,value, # do something to item # do something to value end


Rust

The for loop has the structure for in . It implicitly calls th
IntoIterator::into_iter
method on the expression, and uses the resulting value, which must implement th

trait. If the expression is itself an iterator, it is used directly by the for loop through a

that returns the iterator unchanged. The loop calls the Iterator::next method on the iterator before executing the loop body. If Iterator::next returns Some(_), the value inside is assigned to the
pattern A pattern is a regularity in the world, in human-made design, or in abstract ideas. As such, the elements of a pattern repeat in a predictable manner. A geometric pattern is a kind of pattern formed of geometric shapes and typically repeated l ...
and the loop body is executed; if it returns None, the loop is terminated. let mut numbers = vec!
, 2, 3 The comma is a punctuation mark that appears in several variants in different languages. It has the same shape as an apostrophe or single closing quotation mark () in many typefaces, but it differs from them in being placed on the baseline o ...
// Immutable reference: for number in &numbers for square in numbers.iter().map(, x, x * x) // Mutable reference: for number in &mut numbers // prints " , 4, 6: println!("", numbers); // Consumes the Vec and creates an Iterator: for number in numbers // Errors with "borrow of moved value": // println!("", numbers);


Scala

// return list of modified elements items map items map multiplyByTwo for yield doSomething(x) for yield multiplyByTwo(x) // return nothing, just perform action items foreach items foreach println for doSomething(x) for println(x) // pattern matching example in for-comprehension for ((key, value) <- someMap) println(s"$key -> $value")


Scheme

(for-each do-something-with a-list) do-something-with is a one-argument function.


Smalltalk

collection do: "do something to item"


Swift

Swift Swift or SWIFT most commonly refers to: * SWIFT, an international organization facilitating transactions between banks ** SWIFT code * Swift (programming language) * Swift (bird), a family of birds It may also refer to: Organizations * SWIFT ...
uses the forin construct to iterate over members of a collection. for thing in someCollection The forin loop is often used with the closed and half-open range constructs to iterate over the loop body a certain number of times. for i in 0..<10 for i in 0...10


SystemVerilog

SystemVerilog SystemVerilog, standardized as IEEE 1800, is a hardware description and hardware verification language used to model, design, simulate, test and implement electronic systems. SystemVerilog is based on Verilog and some extensions, and since 20 ...
supports iteration over any vector or array type of any dimensionality using the foreach keyword. A trivial example iterates over an array of integers: A more complex example iterates over an associative array of arrays of integers:


Tcl

Tcl uses foreach to iterate over lists. It is possible to specify more than one iterator variable, in which case they are assigned sequential values from the list. It is also possible to iterate over more than one list simultaneously. In the following i assumes sequential values of the first list, j sequential values of the second list:


Visual Basic .NET

For Each item In enumerable ' Do something with item. Next or without
type inference Type inference refers to the automatic detection of the type of an expression in a formal language. These include programming languages and mathematical type systems, but also natural languages in some branches of computer science and linguistic ...
For Each item As type In enumerable ' Do something with item. Next


Windows


Conventional command processor

Invoke a hypothetical frob command three times, giving it a color name each time. C:\>FOR %%a IN ( red green blue ) DO frob %%a


Windows PowerShell

foreach ($item in $set) From a pipeline $list , ForEach-Object # or using the aliases $list , foreach $list , %


XSLT


See also

*
Do while loop In most computer programming languages a do while loop is a control flow statement that executes a block of code and then either repeats the block or exits the loop depending on a given boolean condition. The ''do while'' construct consists o ...
*
For loop In computer science a for-loop or for loop is a control flow statement for specifying iteration. Specifically, a for loop functions by running a section of code repeatedly until a certain condition has been satisfied. For-loops have two part ...
*
While loop In most computer programming languages, a while loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. The ''while'' loop can be thought of as a repeating if statement. Overview The '' ...
*
Map (higher-order function) In many programming languages, map is the name of a higher-order function that applies a given function to each element of a collection, e.g. a list or set, returning the results in a collection of the same type. It is often called ''apply- ...


References

{{Reflist, 2 Articles with example Ada code Articles with example Perl code Articles with example PHP code Articles with example Python (programming language) code Articles with example Racket code Articles with example Smalltalk code Articles with example Tcl code Control flow Programming language comparisons Articles with example Java code Articles with example Haskell code ru:Цикл просмотра>1;2;3;4, ;


ParaSail

The
ParaSail Parasailing, also known as parascending, paraskiing or parakiting, is a recreational kiting activity where a person is towed behind a vehicle while attached to a specially designed canopy wing that resembles a parachute, known as a parasail w ...
parallel programming language supports several kinds of iterators, including a general "for each" iterator over a container: var Con : Container := ... // ... for each Elem of Con concurrent loop // loop may also be "forward" or "reverse" or unordered (the default) // ... do something with Elem end loop ParaSail also supports filters on iterators, and the ability to refer to both the key and the value of a map. Here is a forward iteration over the elements of "My_Map" selecting only elements where the keys are in "My_Set": var My_Map : Map Univ_String, Value_Type => Tree> := ... const My_Set : Set := abc", "def", "ghi" for each tr => Trof My_Map forward loop // ... do something with Str or Tr end loop


Pascal

In Pascal, ISO standard 10206:1990 introduced iteration over set types, thus: var elt: ElementType; eltset: set of ElementType; for elt in eltset do


Perl

In
Perl Perl is a family of two high-level, general-purpose, interpreted, dynamic programming languages. "Perl" refers to Perl 5, but from 2000 to 2019 it also referred to its redesigned "sister language", Perl 6, before the latter's name was offic ...
, ''foreach'' (which is equivalent to the shorter for) can be used to traverse elements of a list. The expression which denotes the collection to loop over is evaluated in list-context and each item of the resulting list is, in turn, aliased to the loop variable. List literal example: foreach (1, 2, 3, 4) Array examples: foreach (@arr) foreach $x (@arr) Hash example: foreach $x (keys %hash) Direct modification of collection members: @arr = ( 'remove-foo', 'remove-bar' ); foreach $x (@arr) # Now @arr = ('foo', 'bar');


PHP

foreach ($set as $value) It is also possible to extract both keys and values using the alternate syntax: foreach ($set as $key => $value) Direct modification of collection members: $arr = array(1, 2, 3); foreach ($arr as &$value) // Now $arr = array(2, 3, 4); // also works with the full syntax foreach ($arr as $key => &$value)
More information


Python

for item in iterable_collection: # Do something with item Python's tuple assignment, fully available in its foreach loop, also makes it trivial to iterate on (key, value) pairs in
associative array In computer science, an associative array, map, symbol table, or dictionary is an abstract data type that stores a collection of (key, value) pairs, such that each possible key appears at most once in the collection. In mathematical terms an a ...
s: for key, value in some_dict.items(): # Direct iteration on a dict iterates on its keys # Do stuff As for ... in is the only kind of for loop in Python, the equivalent to the "counter" loop found in other languages is... for i in range(len(seq)): # Do something to seq ... though using the enumerate function is considered more "Pythonic": for i, item in enumerate(seq): # Do stuff with item # Possibly assign it back to seq


R

for (item in object) As for ... in is the only kind of for loop in R, the equivalent to the "counter" loop found in other languages is... for (i in seq_along(object))


Racket

(for ( tem set (do-something-with item)) or using the conventional Scheme for-each function: (for-each do-something-with a-list) do-something-with is a one-argument function.


Raku

In Raku, a sister language to Perl, ''for'' must be used to traverse elements of a list (''foreach'' is not allowed). The expression which denotes the collection to loop over is evaluated in list-context, but not flattened by default, and each item of the resulting list is, in turn, aliased to the loop variable(s). List literal example: for 1..4 Array examples: for @arr The for loop in its statement modifier form: .say for @arr; for @arr -> $x for @arr -> $x, $y Hash example: for keys %hash -> $key or for %hash.kv -> $key, $value or for %hash -> $x Direct modification of collection members with a doubly pointy block, ''<->'': my @arr = 1,2,3; for @arr <-> $x # Now @arr = 2,4,6;


Ruby

set.each do , item, # do something to item end or for item in set # do something to item end This can also be used with a hash. set.each do , item,value, # do something to item # do something to value end


Rust

The for loop has the structure for in . It implicitly calls th
IntoIterator::into_iter
method on the expression, and uses the resulting value, which must implement th

trait. If the expression is itself an iterator, it is used directly by the for loop through a

that returns the iterator unchanged. The loop calls the Iterator::next method on the iterator before executing the loop body. If Iterator::next returns Some(_), the value inside is assigned to the
pattern A pattern is a regularity in the world, in human-made design, or in abstract ideas. As such, the elements of a pattern repeat in a predictable manner. A geometric pattern is a kind of pattern formed of geometric shapes and typically repeated l ...
and the loop body is executed; if it returns None, the loop is terminated. let mut numbers = vec!
, 2, 3 The comma is a punctuation mark that appears in several variants in different languages. It has the same shape as an apostrophe or single closing quotation mark () in many typefaces, but it differs from them in being placed on the baseline o ...
// Immutable reference: for number in &numbers for square in numbers.iter().map(, x, x * x) // Mutable reference: for number in &mut numbers // prints " , 4, 6: println!("", numbers); // Consumes the Vec and creates an Iterator: for number in numbers // Errors with "borrow of moved value": // println!("", numbers);


Scala

// return list of modified elements items map items map multiplyByTwo for yield doSomething(x) for yield multiplyByTwo(x) // return nothing, just perform action items foreach items foreach println for doSomething(x) for println(x) // pattern matching example in for-comprehension for ((key, value) <- someMap) println(s"$key -> $value")


Scheme

(for-each do-something-with a-list) do-something-with is a one-argument function.


Smalltalk

collection do: "do something to item"


Swift

Swift Swift or SWIFT most commonly refers to: * SWIFT, an international organization facilitating transactions between banks ** SWIFT code * Swift (programming language) * Swift (bird), a family of birds It may also refer to: Organizations * SWIFT ...
uses the forin construct to iterate over members of a collection. for thing in someCollection The forin loop is often used with the closed and half-open range constructs to iterate over the loop body a certain number of times. for i in 0..<10 for i in 0...10


SystemVerilog

SystemVerilog SystemVerilog, standardized as IEEE 1800, is a hardware description and hardware verification language used to model, design, simulate, test and implement electronic systems. SystemVerilog is based on Verilog and some extensions, and since 20 ...
supports iteration over any vector or array type of any dimensionality using the foreach keyword. A trivial example iterates over an array of integers: A more complex example iterates over an associative array of arrays of integers:


Tcl

Tcl uses foreach to iterate over lists. It is possible to specify more than one iterator variable, in which case they are assigned sequential values from the list. It is also possible to iterate over more than one list simultaneously. In the following i assumes sequential values of the first list, j sequential values of the second list:


Visual Basic .NET

For Each item In enumerable ' Do something with item. Next or without
type inference Type inference refers to the automatic detection of the type of an expression in a formal language. These include programming languages and mathematical type systems, but also natural languages in some branches of computer science and linguistic ...
For Each item As type In enumerable ' Do something with item. Next


Windows


Conventional command processor

Invoke a hypothetical frob command three times, giving it a color name each time. C:\>FOR %%a IN ( red green blue ) DO frob %%a


Windows PowerShell

foreach ($item in $set) From a pipeline $list , ForEach-Object # or using the aliases $list , foreach $list , %


XSLT


See also

*
Do while loop In most computer programming languages a do while loop is a control flow statement that executes a block of code and then either repeats the block or exits the loop depending on a given boolean condition. The ''do while'' construct consists o ...
*
For loop In computer science a for-loop or for loop is a control flow statement for specifying iteration. Specifically, a for loop functions by running a section of code repeatedly until a certain condition has been satisfied. For-loops have two part ...
*
While loop In most computer programming languages, a while loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. The ''while'' loop can be thought of as a repeating if statement. Overview The '' ...
*
Map (higher-order function) In many programming languages, map is the name of a higher-order function that applies a given function to each element of a collection, e.g. a list or set, returning the results in a collection of the same type. It is often called ''apply- ...


References

{{Reflist, 2 Articles with example Ada code Articles with example Perl code Articles with example PHP code Articles with example Python (programming language) code Articles with example Racket code Articles with example Smalltalk code Articles with example Tcl code Control flow Programming language comparisons Articles with example Java code Articles with example Haskell code ru:Цикл просмотра