TransWikia.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!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP