I am a python newbie and am attempting to write code for sieve of Eratosthenes. For this I have to initialize a list of empty sets. I tried doing this factors=[set()]*1001
, but this produces a shallow copy. I want a deep copy, so that factors[i]
and factors[j]
point to different sets. Is there a simple syntax for doing that?
You can create an empty list using an empty pair of square brackets [] or the type constructor list() , a built-in function that creates an empty list when no arguments are passed. Square brackets [] are commonly used in Python to create empty lists because it is faster and more concise.
Empty lists are considered False in Python, hence the bool() function would return False if the list was passed as an argument. Other methods you can use to check if a list is empty are placing it inside an if statement, using the len() methods, or comparing it with an empty list.
Advantages of Python SetsBecause sets cannot have multiple occurrences of the same element, it makes sets highly useful to efficiently remove duplicate values from a list or tuple and to perform common math operations like unions and intersections.
factors = [set() for index in xrange(1001)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With