Home > Blockchain >  How to perform operation on specific elements of a list?
How to perform operation on specific elements of a list?

Time:02-10

So, I want the odd numbers of the list to be multiplied by two and form a new list with the same index value but no other changes in the initial list, for example i is the initial list and o is the output i want

i=['0','7','2','3','4']
o=['0','14','2,'6','4']

here's the code I tried:

list=["1","3","7"]

for num in list:

    if num%2!=0:

        num*2

print(list)

here's the error I get:

PS C:\Users\suhas\Desktop\sujan> & C:/Users/suhas/AppData/Local/Programs/Python/Python39/python.exe c:/Users/suhas/Desktop/sujan/user_testing.py
Traceback (most recent call last):
  File "c:\Users\suhas\Desktop\sujan\user_testing.py", line 5, in <module>
    if num%2!=0:
TypeError: not all arguments converted during string formatting

CodePudding user response:

ls = ['1', '2', '3']

for i, el in enumerate(ls):
  if int(el) % 2:
    ls[i] = str(int(el)*2)

print(ls)
# prints ['2', '2', '6']

If you intend to not mutate the input list and create a new list for the results:

ls = ['1', '2', '3']
res = []

for el in ls:
  if int(el) % 2:
    res.append(str(int(el)*2))
  else:
    res.append(el)

print(res)
# prints ['2', '2', '6']

If the input list were only integers you wouldn't need to convert the elements to integers and back to strings, of course:

ls = [1, 2, 3]

for i, el in enumerate(ls):
  if el % 2:
    ls[i] = el*2

print(ls)
# prints [2, 2, 6]

Please avoid naming your lists list. This shadows the list type of python and can create a lot of confusion and subtle bugs later on.

CodePudding user response:

Your error comes from the comparison if num%2!=0: where num is a str-type and 0 is an integer. To check this you can use the type function, returning what type your variable num is;

list=["1","3","7"]

for num in list:
    print(type(num))
    if num%2!=0:

        num*2

print(list)

instead of looping through the list and saving each element as a variable, you want to iterate through a range with the length of your list. By doing so you can use the number in the range to access the index of each element of the list instead and updating the lists element if your criteria is met;

list = ['0','7','2','3','4']
# wanted output ['0','14','2','6','4']

for i in range(len(list)):
    num = int(list[i])
    
    if num%2 != 0:
        list[i] = num*2

print(list)

Read some about loops and lists to get the syntax right for next try :) w3school Python - Loop Lists

CodePudding user response:

Example is a little misleading here. If we consider odd indices then

o=[int(i[x])*2 if x%2==1 else int(i[x]) for x in range(len(i))]

If we consider numbers themselves

o= [str(int(x)*2) for x in i if int(x)%2!=0]

CodePudding user response:

The below approach uses a list comprehension to achieve the desired list. Here, if we consider in_list as input list then no. inside list is stored as a string so while iterating over the list to check whether no. is odd or even first no. needs to be converted to int and then it is checked with % operator if it is even then it's multiplied with 2 and then result is converted back to string as the output requirement is a list of numbers stored as a string

in_list=['0','7','2','3','4']
output = [i if (int(i)%2)==0 else str(int(i)*2) for i in in_list ]
print(output)
  • Related