Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 825
user2713373 Avatar asked Feb 18 '26 14:02

user2713373


1 Answers

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)

like image 142
keyser Avatar answered Feb 21 '26 13:02

keyser



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!