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]
Related
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
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
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]
Let's say I have a list, mylist, and I define it to be [1, 2, 3, 4, 5]. How is there a simple way to double every element of the list from within a for loop?
I know you could do something like:
for i in range(len(mylist)):
mylist[i] *= 2
I also know that you could make a list comprehension:
mylist = [2*i for i in range(1, 6)
But is there a way to do it like this?
for num in mylist:
#code goes here
I tried doing something like:
for num in mylist:
num *= 2
but num is a local variable, so this doesn't modify mylist, just num. Does anyone know a good way to do this?
The usual way to do this is with a list comprehension, iterating directly over the list items, not indirectly via an index.
mylist = [1, 2, 3, 4, 5]
mylist = [2 * num for num in mylist]
print(mylist)
output
[2, 4, 6, 8, 10]
That replaces mylist with a new list object. That's generally ok, but sometimes you want to modify the existing object, eg when other objects have a reference to mylist. You can do that with a slice assignment.
mylist[:] = [2 * num for num in mylist]
It's not really possible since you shouldn't try to change a list while looping through it in that way. I would stick with your other two ways of manipulating the list
Using an explicit for loop. Use enumerate while iterating and assign a new value to each item.
mylist = [1, 2, 3, 4, 5]
for i, n in enumerate(mylist):
mylist[i] = n * 2
Just be careful - don't change the number of items in a list: Remove items from a list while iterating
a = [2, 2, 4, 2, 5, 7]
If one is to find the minimum value in this list (which is 2) the corresponding indexes of 2 in the list a are 0, 1 and 3 respectively.
How to tell python to use the minimum value at the highest index (the number 2 at index 3)?
You can simply reverse the list using a[::-1] and then apply the same technique to find the index. a[::-1].index(min(a)) will give us the index of minimum value from the end, in order to record the index w.r.t to 0th position(starting of list) we can subtract a[::-1].index(min(a)) from len(a) - 1.
a = [2, 2, 4, 2, 5, 7]
print len(a) - a[::-1].index(min(a)) - 1
>>> 3
use enumerate reversing the list with a start index of 1 calling next in the generator to get the first value, subtracting the index from the length of the list.
a = [2, 2, 3, 2, 5, 7]
mn = min(a)
print(len(a) - next(i for i, ele in enumerate(reversed(a),1) if ele == mn))
3
>>> -min(zip(a, range(0, -len(a), -1)))[1]
3
This can be written as a function indexes() and then take the max() of the resulting iterator:
Example:
def indexes(xs, value):
for i, x in enumerate(xs):
if x == value:
yield i
a = [2, 2, 4, 2, 5, 7]
print max(indexes(a, min(a))) # 3
Update; Just as a matter of completeness; if you per se wanted the minimum index for a set of values with more than one minimum you'd just swap out max() for min() at the front of the expression. So:
a = [2, 2, 1, 4, 2, 1, 5, 7]
print min(indexes(a, min(a))) # 2
whilst:
print max(indexes(a, min(a))) # 5
This is kind of handy and flexible in general :)
This might do:
(len(a) -1 )- a[: : -1].index(min(a))
Iterate through the enumerated list and use the maximum index :
In [109]: max([ind for ind, val in enumerate(a) if val==min(a)])
Out[109]: 3
Find the smallest, then iterate over the list collecting the indices of the matching values.
smallest = min(items)
indices = [index for index, value in enumerate(items) if value == smallest]
largest_index = max(indices) # or indices[-1]
If you have a very long list then you might want to start from the back and stop once you reach the first item.
largest_index = len(items) - next(index for index, value in \
enumerate(reversed(items), start=1) if value == smallest)
Try this:
a=[2,2,4,2,5,7]
minval=min(a) #min of a
for l in range(len(a)):
if a[l]==minval:
index=l
continue
print index