Search code examples
pythonlistlist-comprehension

How to print all the n value of of all sublists within a list with lenght >= n when the lenght of other sublists within the same list are < n?


For example, if I want to print the second value of all sublists within a list, I would just call the index 1 of each sublist with a list comprehension.

>>>list = [[1,2],[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3]]
>>>print([value[1] for value in list])
[2, 2, 2, 2, 2]

But I want to print the fourth value of all sublists that have a length >= 4 and get an output like the one below. Obviously, when I try this, I get an index error because not all sublists have a length of four. Desired output:

>>>list = [[1,2],[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3], [1,2,3,4,5,6]]
>>>print([value[3] for value in list])
[4, 4, 4, 4]

I know I could just call individually each value of each sublist but is there a way to do this with list comprehension or another method that can be used with a big list of sublists with unknown lengths for each one?


Solution

  • You could add an if in list comprehension. See list comprehension in glossary document.

    list = [[1,2],[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3], [1,2,3,4,5,6]]
    print([value[3] for value in list if len(value) >= 4])
    # result
    # [4, 4, 4, 4]