2

I'm trying to re-write the following in a list comprehension, but I'm struggling to add the counter in:

create_list = []
    counter = 0
    for x in my_list:
        create_list.append(f(x+counter))
        counter += 1

I've tried:

create_list = [f(x+counter) for x in my_list] but obviously this doesn't increase the counter.

George
  • 33
  • 1
  • 4
  • 3
    Are you looking for `enumerate()` ? – Jan May 13 '18 at 11:37
  • How could I use enumerate() to complete this? – George May 13 '18 at 11:38
  • Correct me if I'm wrong, but wouldn't your counter always be the same as the length `my_list` or more accurately, `create_list`? Or is there some additional logic that is just not in this example? – Lix May 13 '18 at 11:38

2 Answers2

8

You could use enumerate():

new_list = [f(val+index) for (index, val) in enumerate(my_list)]
NPE
  • 486,780
  • 108
  • 951
  • 1,012
0

Okay, this is definitely not the best way to handle it (I hate having to import stuff!), but it's pretty cool and works:

counter = -1

def g(x): # function with side-effect! returns back the value.
    global counter
    counter = counter + 1
    return counter

create_list = [f(x)+g(x)) for x in my_list] #btw you might want to type cast? I don't really know your data sets nor functionality of f, so I'm not sure

There are a lot of other ways too such as making a second list based off the len(my_list) and then using zip to sort of "parallel" compute, or using two list comprehensions, etc.

shanshine
  • 144
  • 9
  • 1
    `enumerate()` is a built-in, no imports needed. And `//` is not a comment in Python. And Python has no type casting. – Martijn Pieters May 13 '18 at 12:05
  • I didn't even think of enumerate(), and I've been using too many languages at once :") – shanshine May 13 '18 at 12:06
  • and by typecasting, I meant like `str(counter)` but I didn't know what my_list was – shanshine May 13 '18 at 12:08
  • That's using a function to produce a different object type. Typecasting is a different process, where the compiler is told to treat data in memory as a different type in a static language, something a dynamic language like Python doesn't need. – Martijn Pieters May 13 '18 at 12:09