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)
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)
you can use list comprehension
list1 = [1,3,4,5,6]
newlist = [x+1 for x in list1]
print(newlist)
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.