I have a list of letters and want to be able to display them vertically like so:
a d
b e
c f
def main():
letters = ["a", "b", "c", "d","e", "f"]
for i in letters:
print(i)
this code only display them like this:
a
b
c
d
e
That's because you're printing them in separate lines. Although you haven't given us enough info on how actually you want to print them, I can infer that you want the first half on the first column and the second half on the second colum.
Well, that is not that easy, you need to think ahead a little and realize that if you calculate the half of the list and keep it: h=len(letters)//2
you can iterate with variable i
through the first half of the list and print in the same line letters[i]
and letters[h+i]
correct? Something like this:
def main():
letters = ["a", "b", "c", "d","e", "f"]
h = len(letters)//2 # integer division in Python 3
for i in range(h):
print(letters[i], letters[h+i])
You can easily generalize it for lists without pair length, but that really depends on what you want to do in that case.
That being said, by using Python you can go further :). Look at this code:
def main():
letters = ["a", "b", "c", "d","e", "f"]
for s1,s2 in zip(letters[:len(letters)//2], letters[len(letters)//2:]): #len(letters)/2 will work with every paired length list
print(s1,s2)
This will output the following in Python 3:
a d
b e
c f
What I just did was form tuples with zip
function grouping the two halves of the list.
For the sake of completeness, if someday your list hasn't a pair length, you can use itertools.zip_longest
which works more or less like zip
but fills with a default value if both iterables aren't of the same size.
Hope this helps!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With