We can describe a data structure as a data organization that involves data management and storage of data in a particular way.
We use list, tuples, dictionary, and set in Python. Let us learn them one by one with various examples.
1. List
A list is a collection of items that are sequential and changeable. The elements of the list do not need to be unique. We declare a list by using [] parenthesis.
inList = [100, 45, 78,1,32]
We can access a list based on the index.
This can be done by using inList[0] to access the first item in the list.
Negative indexing can be used to access elements from the end.
For example, inList[-2] will be used to access the second from the last element in the list.
When we want to access the range of elements in the list we use the following method by specifying the ‘:’. if the start or end is not specified then we assume that it starts from the beginning or till the end based on whichever is not specified.
print(inList[2:4])
Update the list
We update the list by accessing the item at an index and change the value.
inList[0] = 300
Run the code and view how the list works!
List has many other methods like:
Method | What does it do |
sort | Sort the list |
reverse | reverse the order of the list |
remove | remove the element with the value specified |
pop | remove an element at a particular position |
insert | add an element at a particular position |
index | get the index of the first element with a specified value |
extend | adds elements to the end of the list. |
copy | return the copy of a list |
clear | removes all the elements from the list |
count | gets the number of elements in the list |
Append | add an element to the end of the list |
I have demonstrated the usage of some methods below. Run the code and play around with all the methods listed above.
I will discuss about Tuples in the next post.
Next: Tuples