Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove empty nested lists - Python

I'm reading in a .csv file to a list and it appends an empty lists, I'm using the code below to do this.

with open('Scores.csv', 'r') as scores:
    reader = csv.reader(scores)
    tscores = [[str(e) for e in r] for r in reader]

It creates a list of nested lists correctly but appends an empty list after every row read in like so:

[[score1, name1], [], [score2, name2], []]

I believe it's reading \n as an empty string which is why I'm getting that, so I tried to remove empty lists using:

tscores = [tscores.remove(x) for x in tscores if x]

which does delete empty nested lists, but it sets all other nested lists that contained data to None i.e. [None, None]. I modified to:

tscores = [tscores.remove(x) for x in tscores if []]

which wipes out all nested lists completely.

How can I read the file with the same output (a list of nested lists) without appending empty lists or how can I remove all empty lists after being read in?

like image 264
PurplProto Avatar asked Jun 13 '26 16:06

PurplProto


2 Answers

I think what you want to do is

tscores = [x for x in tscores if x != []]

which make a list of only the none empty lists in tscores

like image 60
m7mdbadawy Avatar answered Jun 16 '26 12:06

m7mdbadawy


Alternative to user2990008's answer, you can not create the empty lists in the first place:

tscores = [[str(e) for e in r] for r in reader if len(r) > 0]
like image 23
Claudiu Avatar answered Jun 16 '26 14:06

Claudiu