user7061693
user7061693

Reputation:

How to print more than one value in a list comprehension?

sent = "this is a fun day"
sent = sent.split()
newList = [ch for ch in sent]
print(newList)
output = ["this" "is","a","fun","day"]

I want to print len of each sent as well and the each word capitalized and output should be

output = [["this", 4, 'THIS'], ["is", 2, "IS"], ["a", 1, "A"], ["fun", 3, "FUN"], ["day", 3, "DAY"]]

Upvotes: 3

Views: 111

Answers (2)

Martijn Pieters
Martijn Pieters

Reputation: 1121356

Your list comprehension should simply produce a list with three items each iteration:

output = [[word, len(word), word.upper()] for word in sent]

Demo:

>>> sent = "this is a fun day"
>>> sent = sent.split()
>>> [[word, len(word), word.upper()] for word in sent]
[['this', 4, 'THIS'], ['is', 2, 'IS'], ['a', 1, 'A'], ['fun', 3, 'FUN'], ['day', 3, 'DAY']]

Upvotes: 3

Mureinik
Mureinik

Reputation: 311053

You can use any expression you want in a list comprehension. In this case, a list:

newList = [[ch, len(ch), ch.upper()] for ch in sent]

Upvotes: 1

Related Questions