Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: How to extend or append multiple elements in list comprehension format?

I'd like to get a nice neat list comprehension for this code or something similar!

extra_indices = []
for i in range(len(indices)):
    index = indices[i]
    extra_indices.extend([index, index + 1, index +2])

Thanks!

Edit* The indices are a list of integers. A list of indexes of another array.

For example if indices is [1, 52, 150] then the goal (here, this is the second time I've wanted two separate actions on continuously indexed outputs in a list comprehension)

Then extra_indices would be [1, 2, 3, 52, 53, 54, 150, 151, 152]

like image 829
Fosa Avatar asked Jun 21 '17 05:06

Fosa


People also ask

How do you append multiple items to a list in Python?

extend to extend the list by multiple values from any kind of iterable, being it another list or any other thing that provides a sequence of values. So you can use list. append() to append a single value, and list. extend() to append multiple values.

How do I add elements to a list in Python list comprehension?

Append method is used to append elements. This adds the element to the end of the list. Looping method of Python program can be performed on multiple elements of a data list at the same time.

Can you append in list comprehension Python?

00:12 But Python has developed a syntax called a list comprehension, which simplifies the code needed to perform that same action. It doesn't use . append() at all, but it's important enough that you really should see it in this course while you're looking at how to populate lists.

How do you extend multiple lists in Python?

Using + operator to append multiple lists at once This can be easily done using the plus operator as it does the element addition at the back of the list.


1 Answers

You can use two loops in list comp -

extra_indices = [index+i for index in indices for i in range(3)]
like image 50
kuro Avatar answered Oct 10 '22 21:10

kuro