Collections List Tuple Set Dictionary in Python

Collections (Arrays) : There are four collection data types in the Python programming language:

List is a collection which is ordered and changeable. Allows duplicate members.
Tuple is a collection which is ordered and unchangeable. Allows duplicate members.
Set is a collection which is unordered and unindexed. No duplicate members.
Dictionary is a collection which is unordered, changeable and indexed. No duplicate members.
To work with collection type, it is useful to understand the properties of that type. Choosing the right type for a particular data set could mean retention of meaning, and, it could mean an increase in efficiency or security.

List : A list is a collection which is ordered and changeable. In Python lists are written with square brackets.

def main() : 
lstEmployee = ["sharjeel", "GOPESH PANDEY", "Rupak"]
print(lstEmployee)

#You access the list items by referring to the index number
print(lstEmployee[1])

#To change the value of a specific item, refer to the index number:
lstEmployee[0] = "AFFAN"
print(lstEmployee)

#Print all items in the list, one by one
for employee in lstEmployee:
print(employee)

#Print the number of items in the list
print(len(lstEmployee))

#To add an item to the end of the list, use the append() method
lstEmployee.append("Adyan")
print(lstEmployee)

#To add an item at the specified index, use the insert() method
lstEmployee.insert(1, "shaghil")
print(lstEmployee)

#The remove() method removes the specified item
lstEmployee.remove("shaghil")
print(lstEmployee)

#The pop() method removes the specified index, (or the last item if index is not specified)
lstEmployee.pop()
print(lstEmployee)

#The del keyword removes the specified index
del lstEmployee[0]
print(lstEmployee)

#The del keyword can also delete the list completely
del lstEmployee

#Using the list() constructor to make a List
lstEmployee = list(("bilali", "affan", "adyan")) # note the double round-brackets
print(lstEmployee)

main()



Tuple : A tuple is a collection which is ordered and unchangeable. In Python tuples are written with round brackets.

def main() : 
lstFriends = ("sharjeel", "GOPESH PANDEY", "Rupak")
print(lstFriends)

#Return the item in position 1
print(lstFriends[1])

#Tuples are unchangeabl: Once a tuple is created, you cannot change its values. 
#lstFriends[1] = "AFFAN"
# The values will remain the same:
print(lstFriends)

#Use For loop : Iterate through the items and print the values
for frnd in lstFriends:
print(frnd)

#To determine how many items a list have, use the len() method
print(len(lstFriends))

"""Add Items
#Once a tuple is created, you cannot add items to it. Tuples are unchangeable.

lstFriends[3] = "affan" # This will raise an error
print(lstFriends)

#Remove and Item : The del keyword can delete the tuple completely
del lstFriends
print(lstFriends) #this will raise an error because the tuple no longer exists


#To execute above section, remove multiline comment (") and run the program
"""

#The tuple() Constructor : Using the tuple() method to make a tuple

lstFriends = tuple(("sharjeel", "gopesh", "affan")) # note the double round-brackets
print(lstFriends)

"""
Searches the tuple for a specified value and returns the position of where it was found
Definition and Usage
The index() method finds the first occurrence of the specified value.
The index() method raises an exception if the value is not found."""

friendName = lstFriends.index("gopesh")
print(friendName)

main()



Set : A set is a collection which is unordered and unindexed. In Python sets are written with curly brackets

def main() : 
#Create a set
lstOrganizations = {"sharjeelswork", "Fiserv", "R Systems"}
print(lstOrganizations) # Sets are unordered, so the items will appear in a random order.
"""Access Items
You cannot access items in a set by referring to an index, since sets are unordered the items has no index.
But you can loop through the set items using a for loop, or ask if a specified value is present in a set, by using the in keyword."""
#Loop through the set, and print the values
for organization in lstOrganizations:
  print(organization)

#Check if "banana" is present in the set
print("gopesh" in lstOrganizations)
"""Change Items
Once a set is created, you cannot change its items, but you can add new items.
Add Items
To add one item to a set use the add() method.
To add more than one item to a set use the update() method."""
lstOrganizations.add("nashit")
print(lstOrganizations)
lstOrganizations.update(["Edynamic", "Sitecore"])
print(lstOrganizations)
#Get the number of items in a set
print(len(lstOrganizations))
#Remove Item : To remove an item in a set, use the remove(), or the discard() method.
lstOrganizations.remove("nashit") #If the item to remove does not exist, remove() will raise an error.
print(lstOrganizations)
#To remove an item, use discard
lstOrganizations.discard("Sitecore") #If the item to remove does not exist, discard() will NOT raise an error.
print(lstOrganizations)

"""You can also use the pop(), method to remove an item, but this method will remove the last item. 
Remember that sets are unordered, so you will not know what item that gets removed. 
The return value of the pop() method is the removed item."""
removedItem = lstOrganizations.pop()
print(removedItem)
print(lstOrganizations)
#The clear() method empties the set
lstOrganizations.clear()
#The del keyword will delete the set completely
del lstOrganizations
#The set() Constructor : It is also possible to use the set() constructor to make a set.
lstOrganizations = set(("sharjeelswork", "Fiserv", "R Systems")) # note the double round-brackets
print(lstOrganizations)
main()



Dictionary : A dictionary is a collection which is unordered, changeable and indexed. In Python dictionaries are written with curly brackets, and they have keys and values.

def main() : 
#Create a Dictionary
dicEmployee = {
  "EmployeeName": "Sharjeel",
  "employeeId": "sha-0123",
  "joiningYear": 2018
}
print(dicEmployee)
#Accessing Items : You can access the items of a dictionary by referring to its key name
employeeName = dicEmployee["EmployeeName"]
print(employeeName)
#Get the value of the "model" key
employeeId = dicEmployee.get("employeeId")
print(employeeId)
#Change the "joiningYear" to 2019
dicEmployee["joiningYear"] = 2019
print(dicEmployee)
#Use for loop to iterate in dictionary values : Print all key names in the dictionary, one by one
for empInfo in dicEmployee:
print(empInfo)
#Print all values in the dictionary, one by one:
for x in dicEmployee:
print(dicEmployee[x])

#You can also use the values() function to return values of a dictionary:
for dicValues in dicEmployee.values():
  print(dicValues)
  
#Loop through both keys and values, by using the items() function
for dicKey, dicValue in dicEmployee.items():
print(dicKey, dicValue)

#Dictionary Length : To determine how many items (key-value pairs) a dictionary have, use the len() method.
print(len(dicEmployee))
#Adding Items : Adding an item to the dictionary is done by using a new index key and assigning a value to it
dicEmployee["employeeDepartment"] = "Information Technologies"
print(dicEmployee)
#Removing Items : There are several methods to remove items from a dictionary
#The del keyword removes the item with the specified key name
del dicEmployee["joiningYear"]
print(dicEmployee)
#The pop() method removes the item with the specified key name
dicEmployee.pop("employeeDepartment")
print(dicEmployee)
#The clear() keyword empties the dictionary:
dicEmployee.clear()
print(dicEmployee)
#The del keyword can also delete the dictionary completely
del dicEmployee
dicEmployee = dict(EmployeeName = "Sharjeel", employeeId= "sha-0123", joiningYear = 2018)
print(dicEmployee)
main()






Comments

Popular posts from this blog

Error : DependencyManagement.dependencies.dependency.(groupId:artifactId:type:classifier)' must be unique: com.adobe.aem:uber-jar:jar:apis -> version 6.3.0 vs 6.4.0

Operators in Asterisk with Linux

ERROR Exception while handling event Sitecore.Eventing.Remote.PublishEndRemoteEventException: System.AggregateExceptionMessage: One or more exceptions occurred while processing the subscribers to the 'publish:end:remote'