Python Tips - 02

What is the output of the print(x) statements in the below example?

>>>x = set(("apple","banana","cherry"))

>>>print(x)

>>>x.add("orange") # adds a single element

>>>print(x)

>>>x.update(["pine apple", "mango", "grapes"]) # iterates over the sequence and adds elements in the sequence

>>>print(x)

output

{'cherry', 'banana', 'apple'}

{'cherry', 'banana', 'orange', 'apple'}

{'orange', 'apple', 'pine apple', 'banana', 'grapes', 'cherry', 'mango'}

Why the elements are not printed in specific order????

ANS: 

  • set is an unordered collection of elements 
  • set is mutable, iterable 
  • set does not contain duplicate elements
  • order of elements in a set is undefined


Comments

  1. Mam,why did you create a set with tuple rather then create directly creating a set?

    ReplyDelete
    Replies
    1. >>>x={"a","b","c"} # This statement creates a set
      >>>type(x) # verified its type

      But I have used set() function for creating a set...
      Both are valid Harish

      Delete

Post a Comment

Popular posts from this blog

Python Tips -06

C Puzzle

Python Tips - 03