M Suleman Tunio
M Suleman Tunio

Reputation: 87

Accessing elements of nested list

What is the wrong with my code:

l = ['a', ['bb', ['ccc', 'ddd'], 'ee', 'ff'], 'g', 'h']
for i in l:
  for j in i:
    print(j)`

The output is:

a
bb
['ccc', 'ddd']
ee
ff
g
h.

But I want this output:

a
bb
ccc ddd
ee
ff
g
h.

What changes should be made?

Upvotes: 3

Views: 954

Answers (5)

Abdul Wahab
Abdul Wahab

Reputation: 49

L = ['a', ['bb', ['ccc', 'ddd'], 'ee', 'ff'], 'g', 'h']
k = 0
for i in L:
    for j in i:
        if k==2:
            for r in j:
                print(r)
                k =k+1
        else:
            print(j)
            k = k+1
        

Upvotes: 1

amir ali
amir ali

Reputation: 111

I'm assuming that you have 3-dimensional list.

l = ['a', ['bb', ['ccc', 'ddd'], 'ee', 'ff'], 'g', 'h']
from functools import reduce

for first in l:
    for sec in first:
        if type(sec) == type(list()):
            iter = str(reduce(lambda x, y: str(x)+' '+str(y), sec))
            print(iter)
        else:
            print(sec)

Upvotes: 1

Matthias Fripp
Matthias Fripp

Reputation: 18625

I'm assuming the rule is "print every item in list l or nested lists within l on its own line, unless a nested contains no sub-lists, in which case, print all its items on one line with spaces between."

If that's right, then this code should work:

l = ['a', ['bb', ['ccc', 'ddd'], 'ee', 'ff'], 'g', 'h']
def print_list(lst):
    if not any(isinstance(x, list) for x in lst):
        # print list of strings on one line
        print(*lst)
        return
    # contains sublists; print or process items one by one
    for x in lst:
        if isinstance(x, list):
            print_list(x)  # process sub-list
        else:
            print(x)

print_list(l)

Upvotes: 3

user15801675
user15801675

Reputation:

As @Barmar mentioned in the comments that j can be list. You can use isinstance to check if the variable if a specific type

l = ['a', ['bb', ['ccc', 'ddd'], 'ee', 'ff'], 'g', 'h']
for i in l:
  for j in i:
      if isinstance(j,list):
          print(*j)
      else:
          print(j)

Upvotes: 1

yunus
yunus

Reputation: 68

if you want to get all array values of different levels in the same level . in the bellow, an example can solve your problem

def find_value(list_):
    for i in list_:
        if isinstance(i,list):
            for j in find_value(i):
                yield j
        else:
            yield i
l = ['a', ['bb', ['ccc', 'ddd'], 'ee', 'ff'], 'g', 'h']
for i in find_value(l):
    print(i)

may you give more information about what do you want?

Upvotes: 1

Related Questions