Wieso ist meine Liste in Python vom Typ "None" wenn ich versuche eine Liste hinzuzufügen?

2 Antworten

Die Methode list.append() gibt immer None zurück, da das die Liste an ihrem Platz verändert. Es wird keine Kopie der neuen Liste zurückgegeben, um dich an dies zu erinnern. Sonst würden evtl. einige Leute eher dazu verleitet werden, zu denken, b wäre die neue Liste und rand weiterhin die alte. Dies ist nicht der Fall, da die Liste rand durch rand.append(sol) verändert wurde.

Wenn du (warum auch immer) auf die Liste rand mit der Variablen b zugreifen möchtest, kannst du...

rand.append(sol)
b = rand

... schreiben. Aber warum möchtest du dann zwei Variablen b und rand für die gleiche Liste haben, statt nur eine Variable?

============

Siehe dazu auch analog:

Why doesn’t list.sort() return the sorted list?
In situations where performance matters, making a copy of the list just to sort it would be wasteful. Therefore, list.sort() sorts the list in place. In order to remind you of that fact, it does not return the sorted list. This way, you won’t be fooled into accidentally overwriting a list when you need a sorted copy but also need to keep the unsorted version around.
If you want to return a new list, use the built-in sorted() function instead. This function creates a new list from a provided iterable, sorts it and returns it. [...]

https://docs.python.org/3/faq/design.html#why-doesn-t-list-sort-return-the-sorted-list

Siehe auch:

Some collection classes are mutable. The methods that add, subtract, or rearrange their members in place, and don’t return a specific item, never return the collection instance itself but None.

https://docs.python.org/3.3/library/stdtypes.html#built-in-types

Von Experte KarlRanseierIII bestätigt

"b" scheint der Wert von rand.append(sol) zu sein.

Was gibt rand.append(sol) zurück? Ja, nichts.

Also ist "b" entsprechend nichts (None).

Woher ich das weiß:Hobby – Ich programmiere sehr gerne und häufig.