How to Convert a List Into a Set in Python

By Marina Martin

Converting a list into a set in Python usually requires just a few lines of code. Before making this change, keep in mind that there are fundamental differences between lists and sets. Both can contain multiple values, but only a list can contain duplicate values -- a set cannot. Additionally, a set can't be indexed, which means you can't pull out the first, last or fifth item from a set the way you can with a list. A set is also unordered, so you may receive values back in a different order each time you retrieve the set.

Step 1

Open the file containing the Python code on which you want to work or load a Python interpreter.

Step 2

Type the following to assign the original list to a variable, if it is not already assigned. For example:fruit = [ banana, orange, pineapple ]

Step 3

Type the following command to convert the list into a set, replacing "fruit" with the variable name assigned to your list:set(fruit)