Book Image

Python Fundamentals

By : Ryan Marvin, Mark Nganga, Amos Omondi
Book Image

Python Fundamentals

By: Ryan Marvin, Mark Nganga, Amos Omondi

Overview of this book

After a brief history of Python and key differences between Python 2 and Python 3, you'll understand how Python has been used in applications such as YouTube and Google App Engine. As you work with the language, you'll learn about control statements, delve into controlling program flow and gradually work on more structured programs via functions. As you settle into the Python ecosystem, you'll learn about data structures and study ways to correctly store and represent information. By working through specific examples, you'll learn how Python implements object-oriented programming (OOP) concepts of abstraction, encapsulation of data, inheritance, and polymorphism. You'll be given an overview of how imports, modules, and packages work in Python, how you can handle errors to prevent apps from crashing, as well as file manipulation. By the end of this book, you'll have built up an impressive portfolio of projects and armed yourself with the skills you need to tackle Python projects in the real world.
Table of Contents (12 chapters)
Python Fundamentals
Preface

Accessing Tuple Elements


Tuples give us various ways to access their elements. These are as follows:

  • Indexing

  • Slicing

Indexing

Similar to lists, we can use the index operator [] to access an element in a tuple by using its index. Tuple indices start at zero, just like those of lists.

Exercise 22: Accessing Tuple Elements Using Indexing

In this exercise, you will see how to use indexing to access tuples:

  1. Create a new pets tuple with the elements dog, cat, and parrot:

    Python 3.6.1 (default, Dec 2015, 13:05:11)
    [GCC 4.8.2] on linux
       pets = 'dog', 'cat', 'parrot' 
  2. Run pets[1] to access the second index:

       pets[1]
    => 'cat'
  3. Try to access an index that is not in the tuple. Python will raise an IndexError, as shown here:

       pets[3]
    Traceback (most recent call last):
      File "python", line 1, in <module>
    IndexError: tuple index out of range
  4. Indices can also be negative. If you use a negative index, -1 will reference the last element in the tuple, -2 will refer to the second from last element in the...