简体   繁体   中英

New to learning python; why is the print for this for-loop different when I use a list comprehension? how do i make the loop be the same?

from my understanding shouldn't the print for X be the same on both? the answer i need is the one that comes from the list-comprehension, which is a new list where every element is -1 from the original list. But the for-loop one only gives 1 element, I also don't know how that element is calculated. Printing x just gives the last element of the list. I'm sure i'm doing something wrong but i'm not sure how to get a list from just using the for-loop. WHAT IS CONFUSING ME is that if the print(x) is part of the for loop it will print the elements of the desired list I need, but NOT in a list, which means the math I wrote works as intended, right?

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


#loop
x=[]
for i in list:
  x=[i-1]
print(x)

#list comprehension

x=[i-1 for i in list]
print(x)

#confusing part where this print will be the same as the comprehension but not in a list form
 x=[]
for i in list:
  x=[i-1]
  print(x)

First thing, list is a protected keyword. You should be using list_ at least (that's the naming convention if you really need to use list as the name).

The second iterates element by element, and prints each of the elements, what you want is in the loop to set each of the elements one by one, and then print x (not inside the loop).

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

x=[]
for i in list_:
  x.append(i-1)
print(x)

You should append like this:

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

#loop
x=[] 
for i in lst: 
    x.append(i-1)
print(x)
#output: [0, 1, 2, 3, 4]

#list comprehension
x=[i-1 for i in lst] 
print(x)
#output: [0, 1, 2, 3, 4]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM