Data structures are basically just that - they are structures which can hold some data together. In other
words, they are used to store a collection of related data.
There are three built-in data structures in Python - list, tuple and dictionary. We will see how to use each
of them and how they make life easier.
List
A list is a data structure that holds an ordered collection of items i.e. you can store a sequence of
items in a list. This is easy to imagine if you can think of a shopping list where you have a list of items
to buy, except that you probbly have each item on a separate line in your shopping list whereas in Python
you put commas in between them.
The list of items should be enclosed in square brackets so that Python understands that you are specifying
a list. Once you have created a list, you can add, remove or search for items in the list. Since, we can
add and remove items, we say that a list is a mutable data type i.e. this type can be altered.
Quick introduction to Objects and Classes
Although, I've been generally delaying the discussion of objects and classes till now, a little explanation
is needed right now so that you can understand lists better. We will still explore this topic in detail in its
own chapter.
A list is an example of usage of objects and classes. When you use a variable i and assign a value to it,
say integer 5 to it, you can think of it as creating an object (instance) i of class (type) int. In fact, you
can see help(int) to understand this better.
A class can also have methods i.e. functions defined for use with respect to that class only. You can use
these pieces of functionality only when you have an object of that class. For example, Python provides
an append method for the list class which allows you to add an item to the end of the list. For example,
mylist.append('an item') will add that string to the list mylist. Note the use of dotted
notation for accessing methods of the objects.
A class can also have fields which are nothing but variables defined for use with respect to that class
only. You can use these variables/names only when you have an object of that class. Fields are also accessed
by the dotted notation, for example, mylist.field .
No comments:
Post a Comment