Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

the code is here:

>>> a = ['xyz']
>>> b = (5,)
>>> a.extend(b)
>>> a
['xyz', 5]

I checked a lot of information,but they both told me that:

list.extend(seq)
seq -- This is the list of elements

I want know why list can extend a tuple.
thx.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
171 views
Welcome To Ask or Share your Answers For Others

1 Answer

If you look at the docstring for extend, you will see that it can be extended by any iterable:

""" L.extend(iterable) -> None -- extend list by appending elements from the iterable """

This means you are not only limited to lists or tuples, but also strings, sets, and other iterables:

for iterable in ('ab', set([1, 2, 3]), {1:2, 3:4}, (0, 1)):
    l = [1]
    l.extend(iterable)
    print(l)

This prints:

[1, 'a', 'b']
[1, 1, 2, 3]
[1, 1, 3] # Note dictionaries iterate over keys by default
[1, 0, 1]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...