Home > OS >  How to access a number within a number
How to access a number within a number

Time:10-14

If i have a list like

list=[1 ,22, 4 ,18, 42]

how do I add 1 to each number that has a 2 in it? So in this case the output would be

[1 ,23, 4 ,18, 43]

Is there a way I can do this by checking if each number within the list contains a 2?

CodePudding user response:

You can check '2' in str each number then plus one like below:

(better don't use built-in function like list as variable name)

>>> lst1 = [1 ,22, 4 ,18, 42]
>>> [item  1 if '2' in str(item) else item for item in lst1]
[1, 23, 4, 18, 43]

Shorter Version by thanks @user2390182:

>>> [item   ("2" in str(item)) for item in lst1]
[1, 23, 4, 18, 43] # <-> [1 0 , 22 1, 4 0, 18 0, 42 1]

# for more explanation
>>> [("2" in str(item)) for item in lst1]
[False, True, False, False, True] # <-> [0,1,0,0,1]

CodePudding user response:

list = [1,22,4,18,42]
for i in range(len(list)):
    if '2' in str(list[i]):
        list[i] =1

in for loop. check '2' and add one.

CodePudding user response:

You can write a function that filters the numbers by the conditions and adds the required value to it, which you can use with the map function to iterate through the list.

def add_to_list(num):
    if "2" in str(num):
        return num   1
    else:
        return num

list_1 = [1 ,22, 4 ,18, 42]

new_list = list(map(add_to_list, list_1))

CodePudding user response:

You can iterate over the list and typecast each number to string. That way you can easily use the in operator to check if 2 is present in that string.

(I am creating a new list for updated values since we might need old values for some other task, but we can do in-place updation as well)

number_list = [1 ,22, 4 ,18, 42]
updated_list = []

for number in number_list:
    if '2' in str(number):
        updated_list.append(number   1)
    else:
        updated_list.append(number)

CodePudding user response:

Cycle through the list with a for loop and add an if condidition inside the loop. Something like this:

if 2 in list_item:
    list_item=list_item 1
  • Related