Why does a comma transform the type into Line2D of an Axes?

Question:

I’m studying matplotlib and I have a question.

Why just putting a comma in var_1, the type of the variable changes completely, it becomes Line2D, while without the comma the type is list ?

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
var_1, = ax.plot([], [])
var_2 = ax.plot([], [])
print(type(var_1), type(var_2))

#<class 'matplotlib.lines.Line2D'> <class 'list'>
Asked By: rafaelcb21

||

Answers:

ax.plot([], [])

is returning a list of length 1. In the first assignment, the comma indicates you’re assigning contents of the list to the variable, similar to

 a, b, c = 1, 2, 3  

or

 a, b, c = [1, 2, 3]

In your case, its the same as

a, = 1,

(Since 1, generates a tuple (list-like object) of length one. )

Answered By: Luce
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.