'Using a function that returns two lists as an argument for plt.plot

Plotting this function that returns two lists. The first way I plot it works fine the second way comes up with a weird multicolored graph. Why does python interpret these two differently?

import numpy as np
import matplotlib.pyplot as plt


def Triangle():
    x_values = [0.0]
    y_values = [0.0]
    pos_step = 0
    neg_step = 0
    for x in range(0, 100):
        pos_step += .01
        neg_step -= .01
        x_values.append(pos_step)
        x_values.append(neg_step)
        y_values.append(pos_step)
        y_values.append(neg_step)
    
    x_values.sort()
    y_values.sort()  
    y_values = [abs(x) for x in y_values]
    
    return x_values, y_values

x,y = Triangle()
plt.plot(x, y)
plt.show()
    
plt.plot(Triangle())
plt.show()
    


Solution 1:[1]

Because in the first option you're unpacking the values. Let me explain:

x, y = something()

This function returns a tuple containing two values, but using the shown syntax you're separating the tuple into two independent variables (x and y).

z = something()

In the other hand, we have the same function that returns a tuple containing two values. But you don't unpack them. So now, z contains a tuple (of two elements, but still a tuple).

The problem is that you are trying to use plt.plot() providing two values, but in the second case you're only providing a tuple. The function can still work, because it expects an arbitrary number of arguments, and it can work it way through to create a plot.

What can you do? Move your unpacking step to plt.plot(): plt.plot(*something()). This SO question contains answers with a lot of useful information about working with this syntax: What does ** (double star/asterisk) and * (star/asterisk) do for parameters?.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1