1

Given a list, how I generate the list separated by a give value

# Problem
items = ["a", "b", "c"]
expected_result = ["a", "separator", "b", "separator", "c"]

# solution should look like

items = [ item, "separator" for item in items]
Katty Kay
  • 51
  • 1
  • 5
  • 2
    Please kindly provide with what you have tried – Drdilyor May 29 '21 at 16:48
  • I tried ```items = [ [item, "separator"] for item in items]``` I ended up with a 2D list – Katty Kay May 29 '21 at 16:50
  • 3
    It might also help if you explain why you want this? If your end goal is to combine the list into a string, you could write `'separator'.join(items)` – Kraigolas May 29 '21 at 16:50
  • 3
    Does this answer your question? [python: most elegant way to intersperse a list with an element](https://stackoverflow.com/questions/5655708/python-most-elegant-way-to-intersperse-a-list-with-an-element) – joshmeranda May 29 '21 at 16:51
  • 1
    This seems like an xy problem. What will you do with the resulting list? Why do you want it? – Asocia May 29 '21 at 16:52
  • I think it is impossible with list comprehensions – Drdilyor May 29 '21 at 16:53
  • please check [this](https://stackoverflow.com/questions/31040525/insert-element-in-python-list-after-every-nth-element) – gowridev May 29 '21 at 16:57
  • I did it using list comprehension, can this be re-opened? or should I link to my solution somehow? – ozerodb May 29 '21 at 17:01
  • This actually can be done with list comprehension. See below: result = [item for raw_item in items for item in [raw_item, 'separator']] – David Kaftan May 29 '21 at 17:06
  • 2
    @DavidKaftan your solution will end up having a trailing 'separator'. My solution, although not very elegant, works fine with both odd and even sized lists. `result = [ items[int(i/2)] if i%2==0 else "separator" for i in range((2*len(items))-1) ]` – ozerodb May 29 '21 at 17:10
  • yeah, I suppose you could also just do `[item for raw_item in items for item in [raw_item, 'separator']][:-1]` – David Kaftan May 29 '21 at 17:16
  • yup, that's also a possibility, i guess it just depends on what the OP is trying to do – ozerodb May 29 '21 at 17:18

1 Answers1

2
items = ["a", "b", "c"]
separated_list = []
for element in items:
    separated_list += [element]
    separated_list += ["separator"]
separated_list = separated_list[:-1]
frab
  • 1,162
  • 1
  • 4
  • 14