AnswerBun.com

How can I access a variable inside a nested array?

Stack Overflow Asked by IntellTanito on December 21, 2020

I’m trying to access a variable in a nested array, but I keep getting an error saying "list index out of range". I’m using something like this:

userlist = [['Number', 'Name', 'Password', 'Balance'], ['1', 'Bob', '12345', '2.34'], ['2', 'Jake', '0000', '2.64']]

I’m trying to print the first term of every array in userlist, so I used this:

for dataset in userlist:
    print (dataset[0])

I expected the output to be

Number
1
2

But instead I get an error. Could someone please help?

Thanks,

2 Answers

There is an empty list lurking inside userlist.

Try

userlist = [[], ['Number', 'Name', 'Password', 'Balance'], ['1', 'Bob', '12345', '2.34'], ['2', 'Jake', '0000', '2.64']]
for dataset in userlist:
    print(dataset[0])

Output:

Traceback (most recent call last):
  File "C:/Users/wil/AppData/Local/Programs/Python/Python37/zrxtz.py", line 3, in <module>
    print(dataset[0])
IndexError: list index out of range

To fix the problem, use a filter of None to filter out the empty lists:

userlist = [[], ['Number', 'Name', 'Password', 'Balance'], ['1', 'Bob', '12345', '2.34'], ['2', 'Jake', '0000', '2.64']]
userlist = filter(None, userlist)
for dataset in userlist:
    print(dataset[0])

Output:

Number
1
2

Correct answer by Ann Zen on December 21, 2020

for i in range(len(userlist)):
    if(len(userlist[i])>0):
       print(userlist[i][0])

Answered by Shivakrishna Gotur on December 21, 2020

Add your own answers!

Related Questions

Keycloak permission to restrict account based resources

0  Asked on December 26, 2020 by james-lin

 

CSS flex, full height sidebar inside a modal?

1  Asked on December 25, 2020 by ddulla

   

Cant loop through List and display in DataTable

1  Asked on December 25, 2020 by finchy70

 

Automate and looping through batch script

2  Asked on December 25, 2020 by nck_505

       

issue connecting Heroku PHP stack to Redis using Predis

0  Asked on December 25, 2020 by rob-edlin

       

Splitting C linked list without making a copy

2  Asked on December 24, 2020

 

Notice Messages Do Not Appear On The Page

1  Asked on December 24, 2020 by cifhai

 

Making comparisons in a HTTPS GET request in node js

0  Asked on December 24, 2020 by thor_

     

SwiftUI Horizontal ScrollView does not scroll

1  Asked on December 23, 2020 by hillinharwich

     

Calling a tab fragment method inside the parent acitivity

0  Asked on December 23, 2020 by aaron-waller

       

Hiding table rows works, but fading out does not

1  Asked on December 23, 2020 by diamondjoe12

       

How to list kubernetes services in k9s?

1  Asked on December 23, 2020 by matthias-m

 

Ask a Question

Get help from others!

© 2022 AnswerBun.com. All rights reserved. Sites we Love: PCI Database, MenuIva, UKBizDB, Menu Kuliner, Sharing RPP