S_Zizzle
S_Zizzle

Reputation: 95

How can I use list comprehension for manipulating array data by index?

I have a piece of code that basically moves each element in a list down by 1 to make room for a new input data later on in the first position as follows:

wave_amp.reverse()

for i in range(len(wave_amp)-1):
    wave_amp[i] = wave_amp[i+1]enter code here

wave_amp.reverse()

How can I perform ths faster using list comprehension, if possible?

Upvotes: 0

Views: 195

Answers (2)

kederrac
kederrac

Reputation: 17322

you can use list.insert:

list.insert(i, x)

Insert an item at a given position. The first argument is the index of the element before which to insert, so a.insert(0, x) inserts at the front of the list, and a.insert(len(a), x) is equivalent to a.append(x).

my_list = [1, 2, 3, 4]
new_input = 100
my_list.insert(0, new_input)

print(my_list)

output:

[100, 1, 2, 3, 4]

or you could insert a default value until you want to fill with the new input

my_list.insert(0, None)

Upvotes: 1

AmirHmZ
AmirHmZ

Reputation: 556

Try this :

wave_amp.insert( 0 , new_item )

The list.insert(index , item) method inserts item in desired index of list. In your case we wanna add the new item in the beginning of list, so we must insert in index = 0.

Or if you wanna make some room and add that item later , you can try this :

# Make some room in list
wave_amp = [None] + wave_amp
# ...
# Some code
# ...
wave_amp[0] = new_data

Upvotes: 1

Related Questions