Joyce
Joyce

Reputation: 43

Taking two lists as input that contain words, to form a tuple with two words, one from each list that have the same starting letter of each word

I've to take two lists as an input which contain words. Using those words I form a tuple using two words, one from each list that contain the same first letter of each word. Then creating a list of those tuples and printing them.

I have a solution, however, I cannot seem to produce the same item twice. Here's an example of what I mean in words.

List A: ['Jack', 'Tim', 'John', 'Ahmed']

List B: ['Julie', 'Tom', 'Henry', 'Harper']

c = input().lower()
d = input().lower()

a = c.split()
b = d.split()

x = []
for i in range(len(a)):
    if a[i][0] == b[i][0]:
        x.append((a[i], b[i]))

print(x)

My Output: [('joy', 'juggle'), ('troy', 'trim')]

Expected Output: [('Jack', 'Julie'), ('John', 'Julie'), ('Tim', 'Tom')]

I'm quite new to learning the language and wasn't quite able to find any similarities to my previous work to find out how I could reiterate through a / b without reproducing the same output.

Upvotes: 0

Views: 470

Answers (3)

Abdelhamid Belarbi
Abdelhamid Belarbi

Reputation: 609

You can try this

[(x, y) for x in A for y in B if x[0] == y[0]]

Upvotes: 0

amanb
amanb

Reputation: 5463

With list comprehensions:

In [50]: a = ['Jack', 'Tim', 'John', 'Ahmed']

In [51]: b = ['Julie', 'Tom', 'Henry', 'Harper']

In [55]: c = [(x,y) for x in a for y in b if x.lower()[0]==y.lower()[0]]

In [56]: c
Out[56]: [('Jack', 'Julie'), ('Tim', 'Tom'), ('John', 'Julie')]

Upvotes: 1

Osman Mamun
Osman Mamun

Reputation: 2882

Use itertools.product to get all the pairs and then filter them out:

In [1]: from itertools import product

In [2]: a =  ['Jack', 'Tim', 'John', 'Ahmed']

In [3]: b = ['Julie', 'Tom', 'Henry', 'Harper']

In [4]: out = [i for i in product(a, b) if i[0][0] == i[1][0]]

In [5]: out
Out[5]: [('Jack', 'Julie'), ('Tim', 'Tom'), ('John', 'Julie')]

Upvotes: 1

Related Questions