How to modify a list in place - python

I want to add 1 to each element in the list without creating new one
i = [1,2,3,4,5]
for each in i:
i[i.index(each)] = each+1
print(i)
but it return like this...
[6,2,3,4,5]
seems that one add one in first element..but I want to add one for each..

lst = [1,2,3,4,5]
for i, x in enumerate(lst):
lst[i] = x + 1
print(lst)
Output
[2, 3, 4, 5, 6]

After incrementing 1 the next time i.index(each) always returns the first element in this case
for idx in range(len(i)):i[idx]+=1

Try using range of len of list
Ex:
i = [1,2,3,4,5]
for each in range(len(i)):
i[each]= i[each]+1
print(i)
Output:
[2, 3, 4, 5, 6]

Related

Multiplying only odd indexes in a for loop

Multiplying only odd indexes with for loop
Why its not working?
myList = [1, 2, 3, 4, 5]
index = 0
for num in myList:
if index % 2 != 0:
num *= 2
index += 1
print(myList) # here the output still the same list
I want the output to be [1, 4, 3, 8, 5]
Edit: I see that you have edited your question, where you fixed the first issue of checking if the items in the list are odd or not. You are however still iterating over the list using for num in myList, which under the hood creates an Iterator which moves over your list. This means that whatever you do with num, you are only modifying num and not myList[index]. In order to modify the list directly, you will need to reference myList[index]. I strongly recommend you look into using enumerate, see my original answer for how to apply it to your use-case.
Your problem is that you are checking if the value inside myList is even or odd instead of its index.
Also, modifying num within the loop does not modify the value in your original list (this can easily be noticed since in the "modified" list the odd values are not multiplied).
Using the range(len()) idiom to loop over your list would yield the following code:
myList = [1, 2, 3, 4, 5]
for idx in range(len(myList)):
if idx % 2 != 0:
myList[idx] *= 2
print(myList)
You could further shorten the loop/assignment by using enumerate and list comprehension:
myList = [1, 2, 3, 4, 5]
myList = [num * 2 if idx % 2 != 0 else num for idx, num in enumerate(myList)]
print(myList)
Your way isn't working because you are not assigning 'num' back into the list.
newList = [v*2 if idx % 2 != 0 else v for idx, v in enumerate(myList)]
There are two issues in the code -
You need to check if the index is odd or even, and not the element.
Modifying num won't modify the corresponding element in the list as it does not reference the element in the list.
myList = [1, 2, 3, 4, 5]
for idx in range(len(myList)):
if idx % 2 != 0:
myList[idx]*=2

Invert the list by exchanging the first and last element, the second and second last, and so on

So Basically the task is to invert the List by changing the first element with the last one, the second one with the second last etc...
This is what i tried, but nothing happend in the end. Do you have any ideas whats not working here or what different approach i should try?
list=[3,6,9,12,15,18,21,24,27,30]
y = 0
x = len(list)-1
while y <= x:
for i in list:
list[y],list[x]=list[x],list[y]
y+=1
x-=1
for i in list:
print(i)
All the other solutions are good approaches, but if you were specifically
asked to write the logic for inverting the list by changing the first element with last element and so on..here,
y = 0
x = len(list)-1
while y < x:
list[y],list[x]=list[x],list[y]
y+=1
x-=1
for i in list:
print(i)
You can do something like this:
def reverse(lst):
# Iterate over the half of the indexes
for i in range(len(lst) // 2):
# Swap the i-th value with the i-th to last value
lst[i], lst[len(lst)-1-i] = lst[len(lst)-1-i], lst[i]
lst = [1, 2, 3, 4, 5]
reverse(lst)
print(lst) # Outputs [5, 4, 3, 2, 1]
lst = [1, 2, 3, 4]
reverse(lst)
print(lst) # Outputs [4, 3, 2, 1]
You can use the reverse() function:
l = [3,6,9,12,15,18,21,24,27,30]
l.reverse()
You can do as follow:
l=[3,6,9,12,15,18,21,24,27,30]
new_l=l[::-1]
The following will invert the order of a list:
>>> l = [3,6,9,12,15,18,21,24,27,30]
>>> l[::-1]
Out[11]: [30, 27, 24, 21, 18, 15, 12, 9, 6, 3]
You can use this code :
for i in sorted(list,reverse=True):
print(i)

How can I increase the value in list

I've wrote the following code
numbers = [1, 2, 3, 4]
lst = [None] * 3
for i in range(0, 3):
lst[i] = numbers[:]
So if I want to increase the value in first lst by 1 and increase the value in second lst my 2 and so on.
Can I solve this question by for loop?
A possible approach:
numbers=[1, 2, 3, 4]
lst = [None] *3
for i in range(0,3):
lst[i] = [x+i+1 for x in numbers]
Here during each iteration we create new lists by adding i+1 to each value in the list, numbers.
For reference this approach is called list comprehension.
You can do this with list comprehension.
numbers = [i+1+a for i,a in enumerate(numbers)]
Where i will be the index number(I added the +1 since it begins with 0), so for index 1 it will add 1, for index 2 it will add 2 and so on..
And a is the value held at the current index.
which will give an output of:
[2, 4, 6, 8]

What am I doing wrong? It shows me that the list index is out of range

I have a given list and I want to add all elements of that list with an odd index to the new list. Here is my code :
def odd_indices(lst):
new_lst = [ lst[i] for i in lst if (i + 2) % 2 != 0 ]
return new_lst
What am I doing wrong?
You might want to take the index instead of the value itself. The list lst contains values and not indices. enumerate helps generating indices. Do like below.
def odd_indices(lst):
new_lst = [ v for i, v in enumerate(lst) if i% 2 != 0 ]
return new_lst
print(odd_indices([1, 2, 4, 5]))
You could slice the list as follows:
lst[1::2]
The general syntax is:
list[start:end:step]
in the list comprehension[lst[i] for i in lst if (i + 2) % 2 != 0] you iterate over items in the list and try to obtain elements from the original list with the respective index i if i+2 is odd.
as mentioned in other replies you can use enumerate to access index and element.
or you can simply use slicing
>>> foo = [1, 2, 3, 4, 5]
>>> foo[1::2]
[2, 4]
Use enumerate to work on index
>>> lst = [0,1,2,3,4,5,6,7,8,9,10]
>>> [value for index, value in enumerate(lst) if index%2 != 0]
[1, 3, 5, 7, 9] # output odd index values
What is the mistake you have done?
Iterating through list.
In each iteration you will get the element of that list.
you are using that element as the index of the list.
EX:
lst = [1,2,3,4,5,6,7,8,9,10]
In above lst, the last element is 10.
lst[10] ---> which does not exists. # Throws out of index range error

Get previous value based in specific item

I am trying a script where we use a list item and then I will get the previous item.
lst = [1, 3, 4, 6, 8, 10]
next_item = next((x for x in lst if x > 6), None)
print next_item #8
This code works correctly for the item after 6. However i need the item before 6.
I am looking in docs for a prev method but i can't find anything related.
Any idea about that?
Assuming by "before" you mean "previous in lst", it is not necessary to use such a complicated way. This
lst[lst.index(6) - 1]
will give
4
while this
lst[lst.index(6) + 1]
will give
8
Of course you should check for index out of bound errors.
You can loop over the reversed list with a reverse condition :
>>> next((i for i in lst[::-1] if i<6),None)
4
If you are looking for the first number larger than 6 in lst, this is one way to do it:
lst = [1, 3, 4, 6, 8, 10]
lst2 =[]
for num in lst:
if num > 6:
lst2.append(num)
lst2.sort()
print lst2[0]
The output is 8

Categories