Python Structures

Python allows you to use simple structures such as lists and tuples, and even lets you build on them by creating sets. You can also create your own class structures and create objects to use in your programs. Each data structure has a different purpose and syntax. Classes provide the most flexibility with what you can do with them, but they are also the most difficult to implement.

  1. Lists

    • A list structure in Python is a group of related values stored together in square brackets, but separated by commas. For example, "[1,2,3,4]" is a list of numbers. You can save any data type in a list, and access them using index values. Python uses zero-indexing, which means the first value has index zero, the second value has index one, and so on. Python has many methods that you can use to modify lists, such as adding or removing items, counting the total number of items and reversing the list order.

    Class Objects

    • Python lets you make custom classes with different functions and methods, then implement them in your program by creating objects. You create one using the "class" keyword followed by a name, then the declaration of class variables and functions. Later in your program, outside of the class code, you create a class object by calling the class, and then you can set and get the various attributes created in the class definition.

    Tuples

    • A Python tuple is a data structure that resembles a list, but has a different function. Typically, a tuple contains at least two items, such as a coordinate pair. However, you can also use them to store records in a database with a fixed number of fields. Tuples are different from lists in that they use circle brackets instead of square brackets. Also, you cannot use methods on tuples such as append or remove.

    Sets

    • A set is a structure that takes an unordered list and removes any duplicate values from it, then lets you query the set to see if certain items exist in it or not, which you cannot do with a list alone. For example, if your list contains student grades 60, 75, 80 and 75 again, when you create a set called 'grades,' only the unique values are added to it. Then, you can query the set by typing '65 in grades,' which returns false, or '80 in grades," which returns true.

Related Searches:

References

Comments

Related Ads

Featured