1

So, I am just trying to solve a problem on hackerrank.com

Here is my code:

if __name__ == '__main__':
    N = int(input())
    num_list = []
    for numberOfCommands in range(N):
        command , * numbers = input().split(" ")
        numbers = [int(i) for i in numbers]
        print(numbers)
        if command == 'insert':
            num_list.insert(numbers[0],numbers[1:])
        elif command == 'print':
            print(num_list)
        else:
            num_list.command(numbers[0])

The problem is when I print list it prints nested lists. What I want is to creating a single list of ints.

iacob
  • 20,084
  • 6
  • 92
  • 119
  • Don't use the name `list`, it already refers to the built-in [`list`](https://docs.python.org/3/library/stdtypes.html#list) type. `list.insert(numbers[0],numbers[1:])` inserts the list slice `numbers[1:]` at index `numbers[0]`. Is that really what you intend? – Patrick Haugh Jun 02 '18 at 16:19
  • changed name list to num_list but the output is same – S. Kalyankar Jun 02 '18 at 16:25
  • 1
    Could you add (as text in your question) what the problem you're trying to solve is? – Patrick Haugh Jun 02 '18 at 16:26
  • Does this answer your question? [How to make a flat list out of list of lists?](https://stackoverflow.com/questions/952914/how-to-make-a-flat-list-out-of-list-of-lists) – iacob Mar 11 '21 at 12:47

1 Answers1

0

You can flatten a list of lists like so:

flat_list = [element for sublist in num_list for element in sublist]
print(flat_list)

Or using the inbuilt itertools.chain:

import itertools

list(itertools.chain.from_iterable(num_list))
iacob
  • 20,084
  • 6
  • 92
  • 119