0

Given two very large lists (about 50K records) list1 = [['a','b','c'],['d','e','f']] and list2 = [['a','r','t'],['d','e','n']] . How to obtain list3 = [['a','b','c','r','t'],['d','e','f','e','n']]

Here I'm joining by comapring the first character of the second list's sublists and taking only one of them in final list

I am new to python I tried

i=0
final=[]
    while (i<len(list1)) :
        for row in list2 :
            if(list1[i][0]==list2[0]) :
                final= row + list[i][1:]

    i+=1

But this does not work

4
  • 1
    Hello and welcome! It looks like you want us to write some code for you. While many users are willing to produce code for a coder in distress, they usually only help when the poster has already tried to solve the problem on their own. A good way to demonstrate this effort is to include the code you've written so far, example input (if there is any), the expected output, and the output you actually get (console output, tracebacks, etc.). The more detail you provide, the more answers you are likely to receive. Check the FAQ and How to Ask. Commented May 16, 2017 at 19:43
  • Post your attempt and we'll tell you how to fix it or do it more efficiently. Commented May 16, 2017 at 19:44
  • Please also explain why the two lists in the result only have five elements each. Commented May 16, 2017 at 19:48
  • 1
    Sorry, I am new here. Edited the question Commented May 16, 2017 at 19:53

1 Answer 1

1
list1 = [['a','b','c'],['d','e','f']]
list2 = [['a','r','t'],['d','e','n']]

print([x+y[1:] for x,y in zip(list1,list2)])

Using list comprehensions, list slicing, and zip() function this can be done rather quickly.

Edited based on comments, use an if case to only allow certain things through:

list1 = [['a','b','c'],['d','e','f']]
list2 = [['a','r','t'],['d','e','n']]

print([x+y[1:] for x,y in zip(list1,list2) if x[0] == y[0]])
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you, I am new here. And sorry for not posting my attempt before
What if I want to join using the condition that the first element of the sublists are same
What happens if they aren't the same ?
It does not print them, loop continues

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.