Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
231 views
in Technique[技术] by (71.8m points)

python - Add all elements of an iterable to list

Is there a more concise way of doing the following?

t = (1,2,3)
t2 = (4,5)

l.addAll(t)
l.addAll(t2)
print l # [1,2,3,4,5]

This is what I have tried so far: I would prefer to avoid passing in the list in the parameters.

def t_add(t,stuff):
    for x in t:
        stuff.append(x)
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Use list.extend(), not list.append() to add all items from an iterable to a list:

l.extend(t)
l.extend(t2)

or

l.extend(t + t2)

or even:

l += t + t2

where list.__iadd__ (in-place add) is implemented as list.extend() under the hood.

Demo:

>>> l = []
>>> t = (1,2,3)
>>> t2 = (4,5)
>>> l += t + t2
>>> l
[1, 2, 3, 4, 5]

If, however, you just wanted to create a list of t + t2, then list(t + t2) would be the shortest path to get there.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...