0

I would like to get such a result [2,4,5,6,7], how can do that? Now i get this: [7]

list1 = [1,3,4,5,6]
for i in range(len(list1)):
   l = []

   # list1[i] = list1[i] + 1

   s = list1[i] + 1
   l.append(s)
print(l)
Adrian Klaver
  • 15,886
  • 2
  • 17
  • 28
  • See answer for best way to do this. Your method failed as you keep on setting `l =[]` for each iteration so you end up with a single element list with the last value of `s`. Put `l = []` just after `list1 = [1,3,4,5,6]` and it will work. Also you can simplify to `for i in list1: ... s = i + 1` – Adrian Klaver Jan 16 '23 at 23:09

2 Answers2

2

you can use list comprehension

list1 = [1,3,4,5,6]
newlist = [x+1 for x in list1]
print(newlist)
wjandrea
  • 28,235
  • 9
  • 60
  • 81
1

If you want to use a loop, you need to put l = [] ahead of it - otherwise you're reintializing it as an empty list at each loop iteration,

list1 = [1,3,4,5,6]

l = []
for el in list1:
   l.append(el + 1)
print(l)

Notice that this code directly loops through elements of list1. This is a preferred way for lists and any other iterables. I recommend you use it whenever practical/possible.

As an alternative to list comprehensions and loops, you can also use a map with a lambda,

list1 = [1,3,4,5,6]

new_list = list(map(lambda x: x+1, list1))

print(new_list)

Note, however, that in most situations, including this one, list comprehension is a better choice. For reasons and details, look up this post.

atru
  • 4,699
  • 2
  • 18
  • 19
  • 2
    It's worth adding that there's no reason to use `list(map(lambda))` all together. It's shorter and clearer to use a list comprehension: `[x+1 for x in list1]`. I wrote [an answer about this](/a/61945553/4518341) with some more details. – wjandrea Jan 16 '23 at 23:55
  • 1
    @wjandrea Thank you! I thought there may be some performance benefits, otherwise in a situation like this I myself would use a comprehension. Though I use maps for type conversions like in your example. I added the map solution as an alternative, for completeness. – atru Jan 17 '23 at 03:07