Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python extend with an empty list bug? [duplicate]

Why does python 2.5.2 have the following behavior

>>>[2].extend([]) == [2] False  >>> [2].extend([]) == None True  $ python --version Python 2.5.2 

I assume I'm not understanding something here, but intuitively I'd think that [2].extend([]) should yield [2]

like image 223
Doug T. Avatar asked Feb 14 '09 20:02

Doug T.


People also ask

Can you extend an empty list Python?

You can add elements to an empty list using the methods append() and insert() : append() adds the element to the end of the list. insert() adds the element at the particular index of the list that you choose.

How do you extend the length of a list in Python?

extends() in Python extends() function takes an argument from the iterable (strin, list, tuple, set, dict) and add each elements at the end of the list. The length of the final list increases by the number of elements present in the iterable argument.

Does extend create a new list Python?

The extend() method takes one argument, a list, and appends each of the items of the argument to the original list. (Lists are implemented as classes. “Creating” a list is really instantiating a class. As such, a list has methods that operate on it.)

What is extend () in Python?

The extend() method adds the specified list elements (or any iterable) to the end of the current list.


1 Answers

Extend is a method of list, which modifies it but doesn't return self (returning None instead). If you need the modified value as the expression value, use +, as in [2]+[].

like image 169
Rafał Dowgird Avatar answered Sep 21 '22 15:09

Rafał Dowgird