user12393724
user12393724

Reputation:

Print comprehension list as string

Suppose I have a comprehension list:

list1 = [("hello","my name"),("is","hayhay")]

How would I print this out using a loop? I tried doing

for line in list1:
   print(line);

But it doesn't work.

Upvotes: 0

Views: 95

Answers (4)

Vishnu Komanduri
Vishnu Komanduri

Reputation: 1

My answer may not be the most efficient but does the job.

Please see below.

Thanks,

list1 = [("hello","my name"), ("is", "hayhay")];
for i in range(len(list1)):
    for j in range(len(list1[0])):
        print(list1[i][j]); 

Upvotes: 0

Kris
Kris

Reputation: 420

If you want to print each tuple:

for i in list1:
    print(i)

('hello', 'my name')
('is', 'hayhay')

If you want to print as a series of strings:

for i in list1:
    for l in i:
        print(l)

hello
my name
is
hayhay

If you want to print as a unified string:

list2 = ""
for i in list1:
    for l in i:
        list2 += l+" "
print(list2)

hello my name is hayhay 

Upvotes: 4

Marsilinou Zaky
Marsilinou Zaky

Reputation: 1047

Python doesn't end lines have ";" You need to unpack the tuple to be able to print the string inside of it, if that's what you trying to achieve

list1 = [("hello","my name"),("is","hayhay")]
for line in list1:
    print(*line)

Upvotes: 0

oppressionslayer
oppressionslayer

Reputation: 7204

You can use this:

list1 = [("hello","my name"),("is","hayhay")]

str='' 
for key,item in dict(list1).items(): 
  str+=key + " " + item + " " 
print(str[:-1]) 

# hello my name is hayhay

Upvotes: 1

Related Questions