1

How do I make a 2-d list into a format where each 1-d list is put in a new line? For example, if I had a 2-d list with integers like:

alist = [[1, 2, 3, 4], [5, 6], [7, 8, 9, 10]]

Without using NumPy, how do you change it into a format like:

[1, 2, 3, 4] [5, 6] [7, 8, 9, 10]

I apologize for my bad description, I am a still quite new to python and help would be greatly appreciated

I tried using for loops like for i in range(len(alist)): for j in range(len(alist[I])): print(a[i][j], end=' ')

But the results I have gotten dont seem to follow the format.

Kelly Bundy
  • 23,480
  • 7
  • 29
  • 65
Tyrnataur
  • 11
  • 2
  • 1
    @BrokenBenchmark While they said "each 1-d list is put in a new line" they also explicitly showed the output `[1, 2, 3, 4] [5, 6] [7, 8, 9, 10]` as one line, even written like that in the markdown. Not up to us to decide which one they actually want. – Kelly Bundy Mar 27 '22 at 18:45
  • 1
    @KellyBundy Fair enough. OP, could you edit the post to clarify the intent here? – BrokenBenchmark Mar 27 '22 at 18:49
  • Possible duplicate (once the output is clarified): [Printing list elements on separate lines](/q/6167731/4518341). Note that the top answer (`"\n".join()`) only works on strings, so use [this answer](/a/6168360/4518341) (`print(*alist, sep='\n')`) or [this answer](/a/6168004/4518341) (`for sublist in alist: print(sublist)`) instead. – wjandrea Mar 27 '22 at 19:28
  • @Kelly The new Ask Question wizard exposes kinda confusing behaviour for code formatting, so it should be safe to assume OP meant what they said but messed up the formatting. For some context, [here's a vaguely similar bug report](https://meta.stackoverflow.com/q/416801/4518341). – wjandrea Mar 27 '22 at 19:35
  • @wjandrea So that wizard combines such lines entered as separate lines into a single line? Hard to believe. And I don't think that assumption is safe. – Kelly Bundy Mar 27 '22 at 19:48
  • @Kelly Believe it, it's buggy as hell :| I can reproduce the problem by pasting the multiline text, selecting it with the mouse (not Ctrl+A, weirdly), clicking **Inline code**, then toggling off **Markdown**. That said, erring on the side of caution is fine by me. – wjandrea Mar 27 '22 at 20:07
  • @wjandrea Well, clicking **inline** code is your mistake, but yeah, the editor should then probably better also make it one line in the markdown. – Kelly Bundy Mar 27 '22 at 22:20

1 Answers1

1

Use a for loop to separate them onto different lines:

for sublist in alist:
    print(sublist)

Alternatively, you can use '\n'.join(), as suggested by AKX:

print('\n'.join(str(sublist) for sublist in alist))

If you want them to be all on the same line, use ' '.join() rather than '\n'.join():

print(' '.join(str(sublist) for sublist in alist))

Additionally, you can use the unpacking operator when calling print(), as pointed out by wjandrea:

print(*alist, sep='\n')
BrokenBenchmark
  • 18,126
  • 7
  • 21
  • 33