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]
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.
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.
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.
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.
You can use two loops in list comp -
extra_indices = [index+i for index in indices for i in range(3)]
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