+ 1

[Python] How to correct my code to remove the empty list from the array?

My code is: arr1=[] raw_input=() print("enter:") while raw_input is not'': raw_input = input() a1 = [int(n) for n in raw_input.split()] arr1.append(a1) print(arr1) enter: 1 2 3 4 5 6 7 8 9 result: [[1, 2, 3], [4, 5, 6], [7, 8, 9], []]

18th Nov 2018, 11:42 PM
Wb Z
Wb Z - avatar
3 Réponses
19th Nov 2018, 12:08 AM
Diego
Diego - avatar
+ 4
This may not be the most efficient way to do it, but what I would recommend doing is creating a for loop that loops through every value of the list while checking the value as it goes along. If it comes across a value that is equal to an empty list (if x == []), then you can use the del method (del list[list.index(x)], assuming x is the variable looping through the list) to delete that element.
19th Nov 2018, 12:04 AM
Faisal
Faisal - avatar
+ 4
Check if raw_input is not empty, combined with try ... except block for handling exceptions. arr1 = [] print("Enter space delimited numbers:") while True: try: raw_input = input() if len(raw_input) < 1: break a1 = [int(n) for n in raw_input.split()] arr1.append(a1) except(ValueError, TypeError): print("Invalid input!") print("Enter only space delimited numbers!") break except EOFError: break if len(arr1): print(arr1) else: print("List is empty")
19th Nov 2018, 4:38 AM
Ipang