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.

4
  • 2
    Do you understand that range(0,6) itself returns a list? Commented Aug 24, 2013 at 10:19
  • 1
    indentation is broken in your code Commented Aug 24, 2013 at 10:20
  • and range(0, 6) == [0, 1, 2, 3, 4, 5] itself: do count = range(0, 6) Commented Aug 24, 2013 at 10:20
  • Provide more information about you problem, some test cases maybe. Commented Aug 24, 2013 at 10:24

6 Answers 6

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)

Sign up to request clarification or add additional context in comments.

Comments

6

Use list.extend:

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

Comments

4

You could just use the range function:

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

Comments

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]

Comments

1

List comprehension

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

Comments

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.