Hannah Ouazzane
Hannah Ouazzane

Reputation: 3

In the for loop why does it not square the last number in the list?

I am trying to create a code that will add up a list of numbers which have been squared. I am pretty new to python, so I was wondering if someone could explain why the list1 produced does not include the last number squared. The list2 always seems to start with 0. Can someone explain why?

import math
list2=[]
values=input("Please enter your vector coordinates")
list1=values.split()
print(list1)


for i in range(len(list1)):
    value=i**2
    list2.append(value)

print(list2)

Upvotes: 0

Views: 45

Answers (2)

inspectorG4dget
inspectorG4dget

Reputation: 114035

list2 always starts with a 0 because the first value of i is always 0. When you call range(len(list1)), you are asking for all the numbers in the sequence 0, 1, 2, 3, ..., N; where N is the number of elements in list1. Note that these are not the specific elements in list1.

Assuming that list1 has numbers in it, creating list2 with the squares of the corresponding numbers can be achieved in this way:

list2 = []
for num in list1:
    v = num**2
    list2.append(v)

There's another error in your code: list1 does not contain numbers as desired. In fact, it contains a bunch of strings (each of which looks like a number) but these are strs, not ints. This is because input returns a string, not ints. Continuing from there, values.split() gives you a list of strings, not a list of numbers. So you'll have to cast them to ints yourself:

list1 = [int(v) for v in values.split()]

Here's how I'd write this code:

list2 = []
values = input("Please enter your vector coordinates")
list1 = list(map(int, values.split()))
print(list1)

for num in list1:
    list2.append(num**2)

print(list2)

Upvotes: 1

Djaouad
Djaouad

Reputation: 22794

i is the index, not the value, you can use either indexing:

for i in range(len(list1)):
    value = list1[i]**2
    list2.append(value)

Or simply use for i in list1:

for i in list1:
    value = i**2
    list2.append(value)

Even simpler with a list comprehension:

list2 = [i ** 2 for i in list1]

Upvotes: 3

Related Questions