Moh'd H
Moh'd H

Reputation: 247

printing a nested list by a while loop

I need to print a nested list by using a while loop. any use of a for loop will give a penalty. My function's output doesn't match the required output.

For example:

print_names2([['John', 'Smith'], ['Mary', 'Keyes'], ['Jane', 'Doe']])

prints out (required output):

John Smith 
Mary Keyes 
Jane Doe

My function:

def print_names2(people):
    name = 0
    while name < len(people):
        to_print = ""
        to_print = people[name]
        print(to_print)
        name += 1

prints out:

['John', 'Smith']
['Mary', 'Keyes']
['Jane', 'Doe']

How can i remove the lists and the strings?

Upvotes: 0

Views: 2352

Answers (3)

Marcin
Marcin

Reputation: 238081

You can use two nested while loopls:

def print_names2(people):
    i = 0    
    while i < len(people):
        sub_list = people[i]
        j = 0;
        while j < len(sub_list):       
            print(sub_list[j], end=' ')
            j += 1;
        i += 1


print_names2([['John', 'Smith'], ['Mary', 'Keyes'], ['Jane', 'Doe']])    
# John Smith Mary Keyes Jane Doe 

Upvotes: 2

amow
amow

Reputation: 2223

print '\n'.join([" ".join(i) for i in people])

or

change your print(to_print) to print(" ".join(to_print))

Upvotes: 0

Vinod Sharma
Vinod Sharma

Reputation: 883

this people[name] gives a list & that's why you are seeing list in the output. You have to fetch the element of people[name] list.

def print_names2(people):
    i = 0
    while i < len(people):
        print " ".join(people[i])
        i += 1

Upvotes: 1

Related Questions