Kai  Long
Kai Long

Reputation: 15

Python print out array into two results

I cant print out the second line

i tried to used divide by 2 and use two for loop to print it,

A=[1,2,3,4,5,6,7,8]
w=len(A)
T=w/2
for i in range(T):
  for ii in range(T):
    print A[ii]


A=[1,2,3,4,5,6,7,8]

i want to print like [1,2,3,4] and [5,6,7,8]

Upvotes: 1

Views: 60

Answers (3)

DirtyBit
DirtyBit

Reputation: 16772

Using slicing:

A=[1,2,3,4,5,6,7,8]

print(A[:len(A)//2])                # print(A[:4])
print(A[len(A)//2:])                # print(A[4:])

OUTPUT:

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

EDIT:

For understanding;

A=[1,2,3,4,5,6,7,8]
w = len(A)

first_part = []
sec_part = []
count = 0                  # counter var to check for the first/sec half of list
for i in range((w)):
     if count < w//2:
          count += 1
          first_part.append(A[i])
     else:
      sec_part.append(A[i])

print(first_part)
print(sec_part)

OUTPUT:

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

Upvotes: 2

Gustav Rasmussen
Gustav Rasmussen

Reputation: 3961

print(A[:int(len(A)/2)], A[int(len(A)/2):])

Upvotes: 0

sanyam
sanyam

Reputation: 96

use list slicing:

A = [1,2,3,4,5,6,7,8]
print A[:len(A)/2]
print A[len(A)/2:]

Output would be:

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

Upvotes: 1

Related Questions