Problem creating a list manipulating function

I’m trying to create a function that takes grouped data, represented as such: list2 = {{0, 3}, {1, 7}, {2, 6}, {3, 4}, {4, 1}} and convert it into ungrouped data like this: list2new = {0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 4}.

I’ve written a code block that produces the result I’m after:

n = 0;
string = "{";
While[n != Length[list2],
 n = n + 1;
 For[i = 0, i < list2[[n, 2]], i++,
  string = string <> ToString[list2[[n, 1]]] <> ", ";]]
string = StringDrop[string, -2] <> "}";
ToExpression[string]

However, now when I try to assign this to a variable or define it as a function it develops errors. For example this code doesn’t work:

UngroupList[in_List] := (
  n = 0;
  string = "{";
  While[n != Length[in],
     n = n + 1;
     For[i = 0, i < in[[n, 2]], i++,
      string = string <> ToString[in[[n, 1]]] <> ", ";]]
    string = StringDrop[string, -2] <> "}";
  ToExpression[string])

UngroupList[list2]

Hoping someone can see what I’m doing wrong here.
Thanks for your time.

First off, I would suggest that you invest a bit of time in getting familiar with the functional and pattern-based programming paradigms that are what make Mathematica so very powerful. Very often newcomers to Mathematica start out programming in ways that are more familiar to them coming from procedural languages like C and so on.

That said, here is a program that does what you want:

In[1]:= list2 = {{0, 3}, {1, 7}, {2, 6}, {3, 4}, {4, 1}} 

Out[1]= {{0, 3}, {1, 7}, {2, 6}, {3, 4}, {4, 1}}

In[2]:= Flatten[Apply[ConstantArray, list2, 1]]

Out[2]= {0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 4}

Rather more straightforward no? :wink:

David’s solution is the better one, but just to show another way

      Flatten @ (Table[ First@#, {Last@#}] & /@ list2)

Ah, yes, much simpler. I feel stupid now. Oh well, live and learn.

Thanks for the help guys, really appreciate it.