Posts: 404
Threads: 94
Joined: Dec 2017
tp=(1,2,3,4,5,6,7,8,9,10)
for i in tp:
lt = []
if tp[i]%2 == 0:
lt.append(tp[i])
else:
pass
tp2 = tuple(lt)
print(tp2) I don't understand why is i out of range.
After change in code I receive the same message
tp=(1,2,3,4,5,6,7,8,9,10)
for i in tp:
lt = []
for i in range(1,11):
if tp[i]%2 == 0:
lt.append(tp[i])
else:
pass
tp2 = tuple(lt)
print(tp2)
Posts: 536
Threads: 0
Joined: Feb 2018
Mar-26-2018, 12:50 AM
(This post was last modified: Mar-26-2018, 12:51 AM by woooee.)
What is the complete error message which shows which line the error is on? Print i right after the for i in tp, and then print tp[i], which will error, so print on a separate line. You don't want 2 statements here as the for i in tp is already accessing the values in tp. There are additional problems in the next for i in tp, but that is for you to figure out.
Posts: 2,953
Threads: 48
Joined: Sep 2016
Mar-26-2018, 02:23 AM
(This post was last modified: Mar-26-2018, 02:40 AM by wavic.)
Because you are using the values from the tuple as an index to the elements in the same tuple.
tp contains 10 elements. But tp[10] is the 11th element ( indexing starts from 0 ) and of course, it doesn't exist.
Change the if statement.
if i % 2 == 0:
lt.append(i) In the first code snippet.
Posts: 404
Threads: 94
Joined: Dec 2017
Mar-26-2018, 08:44 PM
(This post was last modified: Mar-26-2018, 09:00 PM by Truman.)
wavic, the output is now (10,)
(Mar-26-2018, 12:50 AM)woooee Wrote: What is the complete error message which shows which line the error is on? Print i right after the for i in tp, and then print tp[i], which will error, so print on a separate line. You don't want 2 statements here as the for i in tp is already accessing the values in tp. There are additional problems in the next for i in tp, but that is for you to figure out.
tp=(1,2,3,4,5,6,7,8,9,10)
for i in tp:
print(i)
print(tp[i])
lt = []
if i%2 == 0:
lt.append(i)
else:
pass
tp2 = tuple(lt)
print(tp2) it gives line 4
Posts: 2,953
Threads: 48
Joined: Sep 2016
Mar-27-2018, 09:27 AM
(This post was last modified: Mar-27-2018, 09:28 AM by wavic.)
Again, do not use the values as an index!
How the output is (10,)? What have you tried exactly?
Here is the same code. You can skip the else statement.
>>> lt = []
>>> tp = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
>>> for i in tp:
... if i % 2 == 0:
... lt.append(i)
... else:
... pass
...
>>> tp2 = tuple(lt)
>>> print(tp2)
(2, 4, 6, 8, 10) I see now that your lt = [] is inside the for loop. So on every iteration you wipe it out to an empty list
Posts: 404
Threads: 94
Joined: Dec 2017
lt = []
tp=(1,2,3,4,5,6,7,8,9,10)
for i in tp:
if i%2 == 0:
lt.append(i)
tp2 = tuple(lt)
print(tp2) Now it works and I completely understand it. Thank you.
|