-3

I want to know if there's a way in python to do something like that:

a=[1,2,3,4,5]

for e in a:

    print e+=[100 if e<4 else 1]

This should print the numbers: 101,102,103,5,6

Thanks in advance

Penneke
  • 65
  • 1
  • 12

3 Answers3

4

List comprehension is one way:

a = [1,2,3,4,5]

b = [x+100 if x < 4 else x+1 for x in a]

[100, 102, 103, 5, 6]

Or as thefourtheye suggested:

b = [x + (100 if x < 4 else 1) for x in a]

Now, as to your code, this is the fix:

for e in a:
    print e+(100 if e<4 else 1) 

You can also do it with map:

>>> map(lambda s: s+(100 if s < 4 else 1), a)
[101, 102, 103, 5, 6]

Remember if you were in Python3, map returns a generator, so you have to list it:

>>> list(map(lambda s: s+(100 if s < 4 else 1), a))
Community
  • 1
  • 1
Iron Fist
  • 10,739
  • 2
  • 18
  • 34
1

To modify the list in place, you'd need to do something like this:

a = [1, 2, 3, 4, 5]

for i, e in enumerate(a):
    a[i] += 100 if e < 4 else 1

print(a)  # -> [101, 102, 103, 5, 6]
Community
  • 1
  • 1
martineau
  • 119,623
  • 25
  • 170
  • 301
0

Try out this

 >>> a = [1,2,3,4,5]
>>> b = [x+100 if x < 4 else x+1 for x in a]
>>> print b
[101, 102, 103, 5, 6]
>>> 
Little Phild
  • 785
  • 1
  • 6
  • 17