2

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.

Dummy00001
  • 16,630
  • 5
  • 41
  • 63
user2713373
  • 31
  • 1
  • 3

6 Answers6

8

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)

Community
  • 1
  • 1
keyser
  • 18,829
  • 16
  • 59
  • 101
6

Use list.extend:

>>> count = [4,5,6]
>>> count.extend([1,2,3])
>>> count
[4, 5, 6, 1, 2, 3]
falsetru
  • 357,413
  • 63
  • 732
  • 636
4

You could just use the range function:

>>> range(0, 6)
[0, 1, 2, 3, 4, 5]
AlexJ136
  • 1,272
  • 1
  • 12
  • 21
4

For an answer without extend...

>>> lst = [1, 2, 3]
>>> lst
[1, 2, 3]
>>> lst += [4, 5, 6]
>>> lst
[1, 2, 3, 4, 5, 6]
Thijs van Dien
  • 6,516
  • 1
  • 29
  • 48
1

List comprehension

>>> g = ['a', 'b', 'c']
>>> h = []
>>> h
[]
>>> [h.append(value) for value in g]
[None, None, None]
>>> h
['a', 'b', 'c']
rsgmon
  • 1,892
  • 4
  • 23
  • 35
0

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]
NeoWang
  • 17,361
  • 24
  • 78
  • 126