2

I have a question.

I have a nested list that looks like this.

x=    [[{'screen_name': 'BreitbartNews',
   'name': 'Breitbart News',
   'id': 457984599,
   'id_str': '457984599',
   'indices': [126, 140]}],
 [],
 [],
 [{'screen_name': 'BreitbartNews',
   'name': 'Breitbart News',
   'id': 457984599,
   'id_str': '457984599',
   'indices': [98, 112]}],
 [{'screen_name': 'BreitbartNews',
   'name': 'Breitbart News',
   'id': 457984599,
   'id_str': '457984599',
   'indices': [82, 96]}]]

There are some empty lists inside the main list. What I am trying to do is to extract screen_name and append them as a new list including the empty ones (maybe noting them as 'null').

y=[]
for i in x :
    for j in i :
        if len(j)==0 :
            n = 'null'
        else :
            n = j['screen_name']
    y.append(n)    

I don't know why the code above outputs a list,

['BreitbartNews',
 'BreitbartNews',
 'BreitbartNews',
 'BreitbartNews',
 'BreitbartNews']

which don't reflect the empty sublist.

Can anyone help me how I can refine my code to make it right?

1
  • your output is this because every dict you have has the same "screen_name" value: BreitbartNews, it never appends null because if the list hasn't any elem you can't iterate over it with j and check it lenght Commented Mar 10, 2021 at 7:07

1 Answer 1

2

You are checking the lengths of the wrong lists. Your empty lists are in the i variables.

The correct code would be

y=[]
for i in x :
    if len(i) == 0:
        n = 'null'
    else:
        n = i[0]['screen_name']
    y.append(n)

It may help to print(i) in each iteration to better understand what is actually happening.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.