As we continue our introductory talks about programming languages, we will introduce new, more complex topics. This article discusses different data structures in Python.
Arrays are also called lists. Traditional arrays in any programming languages are value containers that hold more than one value, all of which share the same type. An integer array of size 10 will hold 10 integer numbers. You should always think of the type of container you want to use for your data to avoid wasted memory and slow execution times. The list’s order in Python is typically changeable. The syntax for defining list in Python is:
days = ["Saturday", "Sunday", Monday"]
There are ways to change the value of a certain spot within the list without redefining the values for the entire list. Accessing the contents of the list can be done using square brackets:
days = ["Saturday", "Sunday", Monday"]
days[1] = "Tuesday"
The command above has altered the value in the first spot in the list so that the list now reads: Tuesday, Sunday, Monday. You can access individual elements in a list using this method. A list can also be created using the constructor list():
days = list(("Saturday", "Sunday", Monday"))
What if we want to add to the list? You can always use the append() method to add an object to the end of the list. You can get rid of the last object in a list by using the remove() method, which removes either a specific object or the last element from the list:
days = list(("Saturday", "Sunday", Monday"))
days.append("Tuesday")
days.remove("Tuesday")
You can always use the len() method to get the length of a given list.
A dictionary is yet another data structure in Python that allows you to add certain values that are associated with tags. Think of the dictionary as a hash table that you can use to learn more information about each element. Each element is called a key, and its associated information is called a value. For example, objects can be assigned colors like with the following dictionary:
mydict = {
"sky": "blue",
"land": "black",
"fire": "yellow"
}
You can also add items to the dictionary through the key:
mydict = dict(sky="blue", land="black", fire="yellow")
Note that we used a constructor method here. Once you have established a dict, you can add a new element:
mydict["snow"] = "white"
Unlike with lists, removing items from dictionaries is done using the del() method:
del(mydict["snow"])
The length of the dictionary can be found by using len() method.
To sum up, the data structures allow you do a lot more with data. You can organize, manage, and use data easily while saving execution time and memory. Want to know more about different programming concepts in Python? Join RoboGarden now. Register for free.