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)
1
  • 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 Commented Jan 16, 2023 at 23:09

2 Answers 2

2

you can use list comprehension

list1 = [1,3,4,5,6]
newlist = [x+1 for x in list1]
print(newlist)
Sign up to request clarification or add additional context in comments.

Comments

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.

2 Comments

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 with some more details.
@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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.