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.
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):
>>> 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].
>>> 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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With