Search code examples
pythoncomplex-numbers

converting an array of arrays of floats to complex numbers


I've got an list of lists each containing the two parts of a complex number, like this:

parts = [[1, 2], [3, 4], [5, 6]]

How do I convert them to a list of complex numbers, like this?

munged = [1+2i, 3+4i, 5+6i]

Solution

  • This should work

    parts = [[1, 2], [3, 4], [5, 6]]
    
    complex_list = [complex(*x) for x in parts]
    
    [(1+2j), (3+4j), (5+6j)]
    

    Note: Each complex number will be a complex object (1+2j). If you need it to be a string '1+2j' or '1+2i'; use:

    # f"{a}+{b}j" or f"{a}+{b}i"
    complex_list = [f"{a}+{b}i" for a, b in parts]
    
    ['1+2i', '3+4i', '5+6i']