Search code examples
pythonlistziplist-comprehension

How to enact split on N element of zipped list


I have a zipped list, with each tuple originally having the same length that looks like this:

[('MATH 441', 'GREAT, LOTS OF HOMEWORK, FUNNY'),(CSCI 519, 'AWFUL, BORING')...]

My goal is to split the second element of the tuple into individual elements based on the comma. From here, each tuple may have different lengths, therefore, I would like to check if the given tuple meets a specific length, and if it does not, enter an 'NAN' element into the tuple.

I imagine we must create a "lists of list", for tuples are immutable so this is what I have created thus far.

master = list(zip(course_codez, lst))
#to make it a list of list, not a list of tuples
master_two = [list(a) for a in zip(course_codez, lst)]
for i in master_two:
    i[1].split(", ")
        

This is the thought process, but I am not entirely sure and would appreciate any help.

Thanks


Solution

  • split() doesn't (can't) modify the element in place, you need to assign the result back to the list element.

    i[1] = i[1].split(", ")
    

    You can do this directly in the list comprehension.

    master_two = [(code, comment.split(", ")) for code, comment in zip(course_codez, lst)]