4

I have a list

a = ["a", "b", "c"]

I want to create a new list with duplicate values with suffix("_ind").

["a", "a_ind", "b", "b_ind", "c", "c_ind"]

I know it can be achieved using the following function(List with duplicated values and suffix)

def duplicate(lst):
    for i in lst:
      yield i
      yield i + "_ind"

How the same functionality can be achieved using generator expression?. I tried with the following code, But it is not working.

duplicate = (i i+'_ind' for i in a) 

File "<stdin>", line 1
duplicate = (i i+'_ind' for i in a)
            ^
SyntaxError: invalid syntax
Abdul Niyas P M
  • 18,035
  • 2
  • 25
  • 46

2 Answers2

3

Use

duplicate = (j for i in a for j in (i, i+'_ind'))
Oluwafemi Sule
  • 36,144
  • 1
  • 56
  • 81
1

When yield are used in the function, they return a value of each yield statement. That means, if you have two yields, each yields will return a single value at each step. However, in the generator expression you can't return two values keeping the return value flat, instead you'll have to return it as tuple. But you can flatten the tuple at the time of extracting value. So, for you case, you may do:

>>> a = ["a", "b", "c"]
>>> duplicate = ((i, i+'_ind') for i in a)
#                 ^ return it as a tuple

>>> [i for s in duplicate for i in s]
['a', 'a_ind', 'b', 'b_ind', 'c', 'c_ind']

OR, you may use the generator expression as mentioned in Oluwafemi Sule's answer

Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126