简体   繁体   中英

Python: Append values to list without for-loop

How can I append values to a list without using the for-loop?

I want to avoid using the loop in this fragment of code:

count = []
for i in range(0, 6):
    print "Adding %d to the list." % i
    count.append(i)

The result must be:

count = [0, 1, 2, 3, 4, 5]

I tried different ways, but I can't manage to do it.

Range:

since range returns a list you can simply do

>>> count = range(0,6)
>>> count
[0, 1, 2, 3, 4, 5]


Other ways to avoid loops ( docs ):

Extend:

>>> count = [1,2,3]
>>> count.extend([4,5,6])
>>> count
[1, 2, 3, 4, 5, 6]

Which is equivalent to count[len(count):len(count)] = [4,5,6] ,

and functionally the same as count += [4,5,6] .

Slice:

>>> count = [1,2,3,4,5,6]
>>> count[2:3] = [7,8,9,10,11,12]
>>> count
[1, 2, 7, 8, 9, 10, 11, 12, 4, 5, 6]

(slice of count from 2 to 3 is replaced by the contents of the iterable to the right)

Use list.extend :

>>> count = [4,5,6]
>>> count.extend([1,2,3])
>>> count
[4, 5, 6, 1, 2, 3]

You could just use the range function:

>>> range(0, 6)
[0, 1, 2, 3, 4, 5]

For an answer without extend ...

>>> lst = [1, 2, 3]
>>> lst
[1, 2, 3]
>>> lst += [4, 5, 6]
>>> lst
[1, 2, 3, 4, 5, 6]

List comprehension

>>> g = ['a', 'b', 'c']
>>> h = []
>>> h
[]
>>> [h.append(value) for value in g]
[None, None, None]
>>> h
['a', 'b', 'c']

You can always replace a loop with recursion:

def add_to_list(_list, _items):
    if not _items:
        return _list
    _list.append(_items[0])
    return add_to_list(_list, _items[1:])

>>> add_to_list([], range(6))
[0, 1, 2, 3, 4, 5]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM