I would like to create a (for) loop that print 2 Array elements for each line. You'll understand better with an example:
array = ["A","B","C","D"]
The output I want is:
A B
C D
How I can do this? Thanks!
I would like to create a (for) loop that print 2 Array elements for each line. You'll understand better with an example:
array = ["A","B","C","D"]
The output I want is:
A B
C D
How I can do this? Thanks!
There are some good posts earlier to learn more about Python looping of list
. Here is a simple way to get what you expected output - regardless of this list has even or odd items.
lst = ['A', 'B', 'C', 'D'] # can add 'E' to try odd number items.
for i, ch in enumerate(lst, 1):
print(ch, end='\t')
if i % 2 == 0: # check to see if it hit the interval threshold?
print() # if you want 3 items in a row, you can change 2 to 3
Output
A B
C D
Iterate through the list and print 2 items with the print command. You can specify 2 as the increment for iterating, and join part of the list, and can handle odd numbers too. The slice of a list goes up to but not including the 2nd number, so slice with i:i+2. At the end of an odd-length list, there will be no 2nd item but the slice won't give an index-out-of-range error:
list1 = ["A","B","C","D","E"]
for i in range(0, len(list1), 2):
print(' '.join(list1[i:i+2]))
to get
A B
C D
E