- Clojure
Select your favorite languages :
- Or search :
Idiom #7 Iterate over list indexes and values
Print each index i with its value x from an array-like collection items
- Ada
- C
- Caml
- C++
- C++
- C++
- C#
- C#
- C#
- D
- D
- Dart
- Dart
- Dart
- Elixir
- Erlang
- Fortran
- Go
- Groovy
- Haskell
- JS
- JS
- Java
- Java
- Java
- Java
- Kotlin
- Lisp
- Lua
- Obj-C
- PHP
- Pascal
- Pascal
- Perl
- Python
- Python
- Ruby
- Ruby
- Rust
- Rust
- Scala
- Scheme
- Smalltalk
- VB
- VB
- VB
for (auto const [i, x] : std::views::enumerate(items)) {
std::cout << i << ": " << x << '\n';
}
Depends on C++ 23
std::size_t i = 0;
for(const auto & x: items) {
std::cout << "Item " << i++ << " = " << x << std::endl;
}
Uses the C++11 features "range-based for loop" and "auto".
foreach (var (i, x) in items.AsIndexed())
{
System.Console.WriteLine($"{i}: {x}");
}
public static class Extensions
{
public static IEnumerable<(int, T)> AsIndexed<T>(
this IEnumerable<T> source)
{
var index = 0;
foreach (var item in source)
{
yield return (index++, item);
}
}
}
By adding an extension method to IEnumerable<T>, we can perform a foreach over the collection.
Such an extension method isn't provided as part of the standard framework but can be added to a project
Such an extension method isn't provided as part of the standard framework but can be added to a project
items.enumerate.each!(a => writeln("i = ", a[0], " value = ", a[1]));
enumerate can be used instead of foreach with an index when the statement is simple enough to be a lambda or when the foreach aggregate (the array like thing) can't be indexed.
items.forEach((val, idx) => {
console.log("index=" + idx + ", value=" + val);
});
This is the functional way of iterating.
range(0, items.length)
.forEach(i -> {
out.println(i + " = " + items[i]);
});
[items enumerateObjectsUsingBlock:^(id x, NSUInteger i, BOOL *stop) {
NSLog(@"Item %lu = %@",(u_long)i,x);
}];
The plain-C approach can be used as well. Showing another, object-oriented possibility. Typecast needed with %lu (same as in printf) for multi-platform compatibility. The stop argument serves same purpose as plain-C break
while (my ($i, $x) = each @items) {
print "array[$i] = $x\n";
}
The each iterator returns the index/key and value as a pair for each iteration.
For i As Integer = 0 To items.Length - 1
Dim x = items(i)
Console.WriteLine($"Item {i} = {x}")
Next
items is an array
For i As Integer = 0 To items.Count - 1
Dim x = items(i)
Console.WriteLine($"Item {i} = {x}")
Next
items is IList(Of T)