Iterating list or array with index

Iterating an array or a list with index while scripting, has it's own purpose.

Before we discuss about iterating an array or a list with index, let's list few of the common scenarios were this is useful :

  • Iterating through lines in a string and keeping track of line number.

  • Zipping two or more arrays into one.

  • If the index is a meaningful position (for example inserting objects in order into the database and updating their sort column etc).

  • Looping over a nested data-structure, say JSON with array elements.

There are many more such scenarios, but felt these are the important once, do feel free to comment on where it was useful for you!

Now let's see some code for Iterating an array or a list with index while scripting :

Iterating a list with index, in python :

for index, item in enumerate( ["A", "B", "C"]):
    print index, item

Iterating an array with index, in ruby :

["A", "B", "C"].each_with_index {|x, y| puts "#{x} => #{y}" }

Iterating an array with index, in perl6 :

my @a = <A B C>;
 
for @a Z 0 .. Inf -> $elem, $index {
 
    say "$elem => $index"
 
}

Iterating an array with index, in javascript :

['A','B','C'].forEach(function(elment,index) { 
    console.log(elment+" => "+index);
});

Iterating an array with index, in bash :

shopt -s extglob
array=('A' 'B' 'C')
for index in ${!array[*]}; do
  echo "${array[$index]} => $index"
done

All the code above shall result in output that is shown below :

A => 0
B => 1
C => 2

Happy Hacking! Keep iterating ;)

Share this