Tanner Purves
Tanner Purves

Reputation: 23

Returning more than one number in a python list

n = [3, 5, 7]

def double_list(x):
    for i in range(0, len(x)):
        x[i] = x[i] * 2
        return x[i]

print double_list(n)

For some reason this python script is only returning the first item in the list instead of all three when it runs... Can someone please help me?!

Upvotes: 1

Views: 143

Answers (5)

Andrew
Andrew

Reputation: 3871

to add to the options:

def double_list(x):
    return map(lambda num: num*2, x)

print double_list([2, 3, 4])

Upvotes: 0

R Sahu
R Sahu

Reputation: 206707

  1. Change the return statement so that it is not indented to be part of the for block.

  2. Return the list instead of an item from the list.

    def double_list(x):
        for i in range(0, len(x)):
            x[i] = x[i] * 2
    
        return x
    

Upvotes: 3

user4401053
user4401053

Reputation:

n = [3, 5, 7]

def double_list(x):
    t=[i*2 for i in x]
    return t

print (double_list(n))

Another short way for that.

Upvotes: 1

Jivan
Jivan

Reputation: 23088

Use a list comprehension instead.

double_list = [ x*2 for x in n ]

Same result, four times shorter, a trillion times more readable.

Because readability counts.

Upvotes: 5

GLHF
GLHF

Reputation: 4035

n = [3, 5, 7]

def double_list(x):
    for i in range(0, len(x)):
        x[i]*=2
    return x

print double_list(n)

Try this.Returning the list, also check how we re-define variables with arithmetical operations.

Upvotes: -4

Related Questions