Reputation: 75
I am having trouble getting the results to produce the integer in the list, not which index it falls under.
#this function takes, as input, a list of numbers and an option, which is either 0 or 1.
#if the option is 0, it returns a list of all the numbers greater than 5 in the list
#if the option is 1, it returns a list of all the odd numbers in the list
def splitList(myList, option):
#empty list for both possible options
oddList = []
greaterList = []
#if option is 0, use this for loop
if int(option) == 0:
#create for loop the length of myList
for i in range(0, len(myList)):
#check if index is greater than 5
if ((myList[i])>5):
#if the number is greater than 5, add to greaterList
greaterList.append(i)
#return results
return greaterList
#if option is 1, use this for loop
if int(option) == 1:
#create for loop the length of myList
for i in range(0, len(myList)):
#check if index is odd by checking if it is divisible by 2
if ((myList[i])%2!=0):
#if index is not divisible by 2, add the oddList
oddList.append(i)
#return results
return oddList
the results I receive are as follows:
>>>splitList([1,2,6,4,5,8,43,5,7,2], 1)
[0, 4, 6, 7, 8]
I am trying to get the results to be [1, 5, 43, 5, 7]
Upvotes: 0
Views: 122
Reputation: 34493
You're iterating over the range of the index. Iterate over the list instead.
for i in myList:
#check if index is greater than 5
if i >5:
#if the number is greater than 5, add to greaterList
greaterList.append(i)
So, your code gets rewritten as (with some minor changes)
def splitList(myList, option):
final_list = []
if int(option) == 0:
for i in myList:
if i > 5:
final_list.append(i)
elif int(option) == 1:
for i in myList:
if i%2 != 0:
final_list.append(i)
return final_list
You could reduce it by doing
def splitList(myList, option):
if int(option) == 0:
return [elem for elem in myList if elem > 5]
elif int(option) == 1:
return [elem for elem in myList if elem % 2 != 0]
Output -
>>> splitList([1,2,6,4,5,8,43,5,7,2], 1)
[1, 5, 43, 5, 7]
Upvotes: 2
Reputation: 320
Take a closer look at your .append() commands... in your compare you're using:
if ((mylList[i])%2!=0)
or
if ((myList[i])>5)
...but when you put it into the list, you're just using
greaterList.append(i)
instead of
greaterList.append(myList[i])
This must be a homework or class somewhere?
Upvotes: 0
Reputation: 58271
List comprehensions greatly simplify your code.
def split_list(xs, option):
if option:
return [x for x in xs if x % 2]
else:
return [x for x in xs if x > 5]
Upvotes: 2
Reputation: 54242
if ((myList[i])>5):
#if the number is greater than 5, add to greaterList
greaterList.append(i)
Instead of adding the index i
, add the value (myList[i]
):
if ((myList[i])>5):
#if the number is greater than 5, add to greaterList
greaterList.append(myList[i])
Same thing for the oddList
case.
Note: @Sukrit Kalra's solution is preferable, but I'm leaving this up to show that there's multiple ways of solving this.
Upvotes: 1