-1

I have an element in follow list as:

  [0.29839835, [734, 805, 679, 758], 'A']

I need to change it to

  [0.29839835, 734, 805, 679, 758, 'A']

Just break the inner set of elements [734, 805, 679, 758] from one elements to 4 elements. Any leads pls?

jpp
  • 159,742
  • 34
  • 281
  • 339
sayan_sen
  • 345
  • 4
  • 15
  • @Chris_Rands, is there a better dupe target? While the target has 49 answers, not one of them has the `itertools` solution, and indeed it's probably because the question there is more generalized. In which case, my answer below wouldn't fit on that question. – jpp Nov 02 '18 at 09:19
  • @jpp 3 solutions on the first page use `itertools` in the dupe target, if you have a better one, then please do add it of course – Chris_Rands Nov 02 '18 at 09:24
  • @Chris_Rands, You misunderstand my point. Adding my solution for **this specific use case** makes no point on the more general question. Because it doesn't answer the question.. While here it does. Don't get me wrong, I'll keep my answer as a community wiki. I just fail to see how someone can look at the answers there and come up with the solution I have below. *Or* how I can add my answer there. – jpp Nov 02 '18 at 09:29
  • @jpp you can re-open this if you want – Chris_Rands Nov 02 '18 at 09:34
  • @jpp,@chris_Rands UPdated the question abit – sayan_sen Nov 02 '18 at 09:35
  • @sayan_sen, I've rolled it back. You shouldn't change your question materially once you've had an answer / answers. Please [ask a new question](https://stackoverflow.com/questions/ask). – jpp Nov 02 '18 at 09:36

2 Answers2

1

For your specific data structure, you can use itertools.chain with a ternary condition:

from itertools import chain

x = [0.29839835, [734, 805, 679, 758], 'A']

res = list(chain.from_iterable([i] if not isinstance(i, list) else i for i in x))

[0.29839835, 734, 805, 679, 758, 'A']

For a generalised solution, see Flatten an irregular list of lists.

jpp
  • 159,742
  • 34
  • 281
  • 339
0

This has already been answered here:

l = [0.29839835, [734, 805, 679, 758], 'A']
a = list()
def flatten(l, a):
    for i in l:
        if isinstance(i, list):
            flatten(i, a)
        else:
            a.append(i)
    return a
print(flatten(l, a))
#[0.29839835, 734, 805, 679, 758, 'A']
New2coding
  • 715
  • 11
  • 23