Lets say I have a list called l1:
l1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
And I want to print it as
[1, 2, 3, 4, 5]
[6, 7, 8, 9, 10]
How would I do that in python on 3.9
I tried to us a \n, but that has not worked for me.
CodePudding user response:
list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(list[:5])
print(list[5:])
outputs:
[1, 2, 3, 4, 5]
[6, 7, 8, 9, 10]
if you want them to be printed on the same line then you can use:
print(list[:5],list[5:])
which will return:
[1, 2, 3, 4, 5] [6, 7, 8, 9, 10]
CodePudding user response:
I guess you wanted to split the main list to subset with a slice of 5,
l1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
r=5
result = [l1[i:i r] for i in range(0,len(l1),r)]
print(result)
Output:
[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]
CodePudding user response:
Slicing would probably work for you.
l1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(l1[:5]) # print first half
print(l1[5:]) # print second half
This should print both halves on separate lines, which is what I think you're trying to do with \n?
[1, 2, 3, 4, 5]
[6, 7, 8, 9, 10]