Lists and Sets

viewTemplate_List = ["- Lost Views (Floor Plans) -", "- Lost Views (Ceiling Plans) -"]
for i in dictFloorPlanViews.values():
for i in dictCeilingPlanViews.values():
viewTemplate_List = set(viewTemplate_List)

I append a list together and put it into a set to remove duplicates from my floor and ceiling dictionary values then run this threw a function. Inside the function is the typical convert to list:

Example 1

if not isinstance(argViewTemplateNames, list):
    argViewTemplateNames = [argViewTemplateNames]

I don’t think the above code is converting the set to a list while the second example does:

Example 2

if not isinstance(argViewTemplateNames, list):
    argViewTemplateNames = list(argViewTemplateNames)

If I feed the below code to example number one, it works.

viewTemplate_List = list(set(viewTemplate_List))

What’s the main difference between calling list() and just using [ ] to create a list and why one works while the other does not?


A few things…

The values() method of your dict already returns a list, so you can write the following instead of using a for loop:

viewTemplate_List = dictFloorPlanViews.values()
viewTemplate_List += dictCeilingPlanViews.values()

You can make a list by doing either of the two:

my_list = []
my_list = list()

However, they are not used identically in other ways. By using bracket notation, you are effectively creating a list which contains any data provided within. The list function either takes no arguments or an iterable. In the second case, it will cast the iterable to a list.

Here are your two examples, but set up a bit differently:

myset = set([1, 1, 1, 2, 3])
if not isinstance(myset, list):
    mylist = [myset]

Doing this makes mylist a list containing a single set like this:

[set([1, 2, 3])]

myset = set([1, 1, 1, 2, 3])
if not isinstance(myset, list):
    mylist = list(myset)

Doing this casts the set to a list:

[1, 2, 3]

So, you may be able to make an empty list using either method, but to actually cast a set (or any other iterable for that matter) to a list, you have to use the list() function.

Actually, you could use a list comprehension if you’d like, but it’s not necessary.

myset = set([1, 1, 1, 2, 3])
mylist = [i for i in myset] # Same as list(myset)
1 Like

@cgartland, Thank you, for the explanation, and the dictionary correction

1 Like