Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

Shane Singh
Shane Singh
5,440 Points

Transposing my array?

I am a novice programmer in python and was wondering if I can get a little help. The code I am about to show below prints out a simple array based on the users input for # of rows and # of columns.

new_list = []

undersc = '_'

for i in range(1, rows + 1):

      new = []

      for j in range(1, columns + 1)     

        new.append(undersc if j > i else 'Z')

      new_list.append(new)

for c in range(len(new_list[0])): 

     print()

for r in range(len(new_list)):

     for c in range(len(new_list[0]))       

       array = print((new_list[r][c]), end=" ")   

     print()

return array

The console outputs the following:

Z _  _  _  _

Z  Z  _  _  _

Z  Z  Z   _  _

I am completely lost as to how I would transpose my array in other words swap the columns with the rows. Any help would be greatly appreciated!

1 Answer

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,423 Points

You have all the information you need. To reverse the columns and rows exchange your inner and outer loops:

# initial print loop
    for r in range(len(new_list)):
        for c in range(len(new_list[0])):
            array = print((new_list[r][c]), end=" ")
        print()


# transposed print loops
    for c in range(columns):
        for r in range(rows):
            array = print((new_list[r][c]), end=" ")
        print()

Compressing and cleaning up your code a bit:

def array2(rows, columns):
    new_list = []
    undersc = '_'

    # i and j are relative counters, no need to use 1-based counting
    for i in range(rows):
        new = []
        for j in range(columns):
            new.append(undersc if j > i else 'Z')
        new_list.append(new)

    # this prints out many blank lines. Not clear why it's needed
    # for c in range(len(new_list[0])):
    #     print()

    for c in range(columns):
        for r in range(rows):
            # print does not return object, assignment to 'array' not needed
            print((new_list[r][c]), end=" ")
        print()

    # no value being returned, explicit 'return' not needed
    # return array

Produces:

>>> array2(3, 4)
Z Z Z 
_ Z Z 
_ _ Z 
_ _ _