---
title: "Iterating List or Array With Index"
description: "Iterating an array or a list with index while scripting, has it’s own purpose. Before we discuss about iterating an array."
url: "https://h3manth.com/scribe/iterating-list-or-array-index/"
canonical_url: "https://h3manth.com/scribe/iterating-list-or-array-index/"
markdown_url: "https://h3manth.com/scribe/blog/iterating-list-or-array-index.md"
publishDate: "2012-06-28T00:00:00.000Z"
author: "Hemanth HM"
category: "python"
tags: ["ruby","python","javascript"]
word_count: 269
reading_time_minutes: 2
x_markdown_tokens: 488
content_signal: "ai-train=yes, search=yes, ai-input=yes"
---

# 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.

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 = ;`

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

```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 ;)
