# list to tuple
# transforming a mutable list into an immutable tuple
>>> myList = [number for number in range(1, 11)]
>>> myTuple = tuple( myList )
>>> print("Type: ", type( myTuple ), ";", "Contents: ", myTuple)
Type:  <class 'tuple'> ; Contents:  (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
 
# tuple to list
# sorting a tuple
>>> tupleOfNumbers = (5, 4, 2, 3, 1)
>>> listOfNumbers = list(tupleOfNumbers)       
>>> listOfNumbers.sort()
>>> listOfNumbers
[1, 2, 3, 4, 5]
>>> newTupleOfNumbers = tuple(listOfNumbers)  
>>> newTupleOfNumbers
(1, 2, 3, 4, 5)
 
 
# list to set
# removing duplicates
>>> myList = [number for number in range(1, 11)]
>>> myList2 = [number for number in range(5, 16)]
>>> myList + myList2
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
>>> mySet = set( myList + myList2 )
>>> mySet
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}
 
# set to frozenset
# making a set immutable
>>> mySet = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}
>>> mySet.add(16)
>>> mySet
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}
>>> myImmutableSet = frozenset( mySet )
>>> myImmutableSet.add(17)
# Traceback information
AttributeError: 'frozenset' object has no attribute 'add'
 
 
# dict to list
# initializing a new dictionary from the keys of an existing dictionary
>>> myDictionary = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5}
>>> myListOfKeys = list( myDictionary.keys() )
>>> myListOfKeys
['one', 'four', 'five', 'three', 'two']
>>> myNewDictionary = dict.fromkeys( myListOfKeys )
>>> myNewDictionary
{'one': None, 'four': None, 'two': None, 'three': None, 'five': None}
Please follow and like us:

0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

RSS
Follow by Email