简体   繁体   中英

Create a list which has only one time each element from two other lists in Python

I'm new in Python and I have to solve a quiz. Given two lists of fruits I have to input the missing code in order to return a new list with unique elements from the 2 lists. So the unique_fruits must have

["apples", "bananas", "pineapples", "cherries", "strawberries", "oranges", "grapes", "watermelon"]

I do not have to care about the order of the list.

So the given problem is the following

def unique_fruits(fruits1, fruits2):
   #write your code here

fruits1 = ["apples", "bananas", "pineapples", "pineapples", "cherries", "strawberries"]
fruits2 = ["oranges", "pineapples", "grapes", "oranges", "cherries", "bananas", "watermelon"]


print(unique_fruits)

My try is the following

    def unique_fruits(fruits1, fruits2):
       unique_fruits = list(set(fruits1 + fruits2))

    fruits1 = ["apples", "bananas", "pineapples", "pineapples", "cherries", "strawberries"]
    fruits2 = ["oranges", "pineapples", "grapes", "oranges", "cherries", "bananas", "watermelon"]

    print(unique_fruits)

But getting error "function unique_fruits at 0x7fd3067ffe18"

I have to write the missing code only were the # is.

The only way to get the result is when I have the following code

def unique_fruits(fruits1, fruits2):
   unique_fruits = list(set(fruits1 + fruits2))

fruits1 = ["apples", "bananas", "pineapples", "pineapples", "cherries", "strawberries"]
fruits2 = ["oranges", "pineapples", "grapes", "oranges", "cherries", "bananas", "watermelon"]
unique_fruits = set(listfruits1 + fruits2))
print(unique_fruits)

But as already mention have to complete my code where # is

What am I missing?

Thanks for your time.

There are a few problems with your code. First of all, function unique_fruits at 0x7fd3067ffe18 isn't an error, it's printing the location in memory of the function because you didn't include () after the function name, or any parameters for the function. Second, instead of defining a variable called unique fruits, you should be returning the value instead. The following works for me, let me know if you have any more questions:

def unique_fruits(fruits1, fruits2):
    return list(set(fruits1 + fruits2))

fruits1 = ["apples", "bananas", "pineapples", "pineapples", "cherries", "strawberries"]
fruits2 = ["oranges", "pineapples", "grapes", "oranges", "cherries", "bananas", "watermelon"]


print(unique_fruits(fruits1, fruits2))

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