Question: I am trying to get a loop like this. Suppose i have 20 rows in table `test` and i need to get its id values inside a loop like below.

```
 <section class="test">
       <div class="n4">

         <div class="n2">
              1 // first row id
         </div>

        <div class="n21">
            2 // second row id
        </div>

    </div>
    </section>

    <section class="test">
       <div class="n4">

         <div class="n2">
              3 // third row id
         </div>

        <div class="n21">
            4 // fourth row id
        </div>

    </div>
    </section> 

      ..... <section> ....upto all ids in the row

```

What i am tried to do is
Suppose table test has 20 rows.

```
    <?php
    $query=$db->query("SELECT * FROM test");  
    $counter=1;
    foreach($query as $row)
    {
    ?>
    <section class="test">
       <div class="n4">

       <?php  if($counter %2 !=0)  ?>     
         <div class="n2">
            <?php echo $row['id']; ?> 
         </div>
         <?php else  ?>
        <div class="n21">
            <?php echo $row['id']; ?>
        </div>

    </div>
    </section>

     <?php
  $counter++;

  } ?>

```

This is not showing the exact result.

Any help please?

Answer: 
In the loop

```
for k,g in itertools.groupby(sorted_data1):

```

`g` is itself an iterator, it's not a collection like a list.

When you call

```
print('key: ',k,' group: ',list(g))

```

inside the loop, the `list(g)` inside the print already goes through the entire iterator `g` to create the list. So, when you call 

```
groups.append(list(g))

```

afterwards, `g` is already "empty" in some sense (more precisely: it is pointing to the end of the iterator), so there's nothing left to put in the list anymore

---

Like DDGG suggested, you can store the results of iterating through `g` once in a more permanent collection (like a `list`) first. Then you can re-use that list multiple times
Just as Dennis said, you can change your code to this to solve the problem:

```
import itertools

data1 = [100, 80, 80, 80, 80, 80, 90, 90, 85, 85, 85]
keys = []
groups = []
sorted_data1 = sorted(data1)

for k, g in itertools.groupby(sorted_data1):
    group = list(g)
    print('key: ', k, ' group: ', group)
    keys.append(k)
    groups.append(group)

print('keys: ', keys)
print('Groups: ', groups)

```