Python Forum

Full Version: Unpacking a list
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Here's some code:

print()
print('This program will print out a set containing all colors from color_list_1 {"White", "Black", "Red"} that are not present in color_list_2 {"Red", "Green"}.')
color_list_1 = set(["White", "Black", "Red"])
color_list_2 = set(["Red", "Green"])
print()
print('Colors meeting stated criteria are {}.'.format(*[i for i in color_list_1 if i not in color_list_2]))
The result of the last line is "Black"

If I leave the asterisk out, the result of the last line is "['Black', 'White']

What happened to White when I tried to unpack the list?

Thanks!
You are passing 2 arguments to .format(). Since your format string only has one placeholder, the second argument is ignored.
Here some variants with f-string.
color_list_1 = set(["White", "Black", "Red"])
color_list_2 = set(["Red", "Green"])
print()
print(f'Colors meeting stated criteria are {[i for i in color_list_1 if i not in color_list_2]}')
print(f'Colors meeting stated criteria are {color_list_1 - color_list_2}')
# Can make sense to make variable outside of string
result = [i for i in color_list_1 if i not in color_list_2]
print(f'Colors meeting stated criteria are: {", ".join(result)}')
Output:
Colors meeting stated criteria are ['White', 'Black'] Colors meeting stated criteria are {'White', 'Black'} Colors meeting stated criteria are: White, Black
You can use oeperator'-' or the difference method
Code:
print('\nThis program will print out a set containing all colors from color_list_1 {"White", "Black", "Red"} that are not present in color_list_2 {"Red", "Green"}.')
color_list_1 = set(["White", "Black", "Red"])
color_list_2 = set(["Red", "Green"])
print(color_list_1 - color_list_2)
print(color_list_1.difference(color_list_2))
Output:
Quote:This program will print out a set containing all colors from color_list_1 {"White", "Black", "Red"} that are not present in color_list_2 {"Red", "Green"}.
{'Black', 'White'}
{'Black', 'White'}