E-Book: Python Programming for Beginners Succinctly | Syncfusion Blogs
Detailed Blog page Skeleton loader

The following chapters are excerpts from Python Programming for Beginners Succinctly, written by Jason Cannon. Look for this upcoming title to be added in early January to the Succinctly series—Syncfusion’s free library of pithy technology books.

Introduction

Choosing a place to begin when learning a new skill can often be difficult, especially when you are dealing with a broad or complex topic. In many cases, there is so much information available that it can be a real challenge to decide exactly where to start. Even worse, you may finally take the first steps toward learning, only to quickly discover far too many concepts, programming examples, and nuances that aren’t fully and thoughtfully explained. This type of experience can be incredibly frustrating, ultimately leaving you with more questions than answers.

Python Succinctly will help you sidestep this frustration. In this book we make no assumptions about your technical background, your knowledge of computer programming, or your general understanding of the Python language. You need no prior knowledge to benefit from reading this book. In these pages you will be guided step-by-step using a logical and systematic approach. While there will be new concepts, code, and jargon introduced, they will be explained in plain language, making it easy for absolutely anyone to understand.

Throughout the book you will be presented with many examples, as well as various Python programs. You can download all of these examples, as well as additional resources, at http://www.LinuxTrainingAcademy.com/python-succinctly.

Let’s get started.

Chapter 7 Tuples

A tuple is an immutable list, meaning that once it is defined it cannot be changed. This is different from normal lists in which you can add, remove, and change the values. With tuples none of these actions are an option. Where tuples are similar to lists is that they are ordered in the same fashion, and the values in the tuple can be still be accessed by index. In fact, you can perform many of the same operations on a tuple that you can on a list. You can concatenate tuples, you can iterate over the values in a tuple with a for loop, you can access values from the end of the tuple using negative indices, and you can access slices of a tuple. Tuples are created using comma separated values between parentheses. The pattern is tuple_name = (item_1, item_2, item_N). If you only want a single item in a tuple, that single item must always be followed by a comma. The pattern is tuple_name = (item_1,).

Tuples are key for organizing and holding data that will not, or should not change at any point during the execution of your program. Using a tuple is a great way to ensure that the values are not accidentally altered. For example, the months of the year should not change.

Code Listing 211

months_of_the_year = (‘January’, ‘February’, ‘March’, ‘April’, ‘May’, ‘June’, ‘July’, ‘August’, ‘September’, ‘October’, ‘November’, ‘December’)

jan = months_of_the_year[0]

print(jan)

print()

for month in months_of_the_year:

    print(month)

# You cannot modify values in a tuple.  This will raise an exception.

Months_of_the_year[0] = ‘New January’

 

Code Listing 212

January

January

February

March

April

May

June

July

August

September

October

November

December

Traceback (most recent call last):

  File “tuples.py”, line 10, in <module>

    months_of_the_year[0] = ‘New January’

TypeError: ‘tuple’ object does not support item assignment

Even though you are unable to change the values within a tuple, you can always remove the entire tuple during the execution of your program by making use of the previously mentioned del statement.
Code Listing 213

months_of_the_year = (‘January’, ‘February’, ‘March’, ‘April’, ‘May’, ‘June’, ‘July’, ‘August’, ‘September’, ‘October’, ‘November’, ‘December’)

print(months_of_the_year)

del months_of_the_year

# This will raise an exception since the tuple was deleted.

Print(months_of_the_year)

Output:

Code Listing 214

(‘January’, ‘February’, ‘March’, ‘April’, ‘May’, ‘June’, ‘July’, ‘August’, ‘September’, ‘October’, ‘November’, ‘December’)

Traceback (most recent call last):

  File “tuples2.py”, line 5, in <module>

    print(months_of_the_year)

NameError: name ‘months_of_the_year’ is not defined

Switching between Tuples and Lists

In order to make a list from a tuple, use the list() built-in function and pass in the tuple. To create a tuple from a list, use the tuple() built-in function. The built-in function type() will display an object’s type.

Code Listing 215

months_of_the_year_tuple = (‘January’, ‘February’, ‘March’, ‘April’, ‘May’, ‘June’, ‘July’, ‘August’, ‘September’, ‘October’, ‘November’, ‘December’)

months_of_the_year_list = list(months_of_the_year_tuple)

print(‘months_of_the_year_tuple is {}.’.format(type(months_of_the_year_tuple)))

print(‘months_of_the_year_list is {}.’.format(type(months_of_the_year_list)))

animals_list = [‘toad’, ‘lion’, ‘seal’]

animals_tuple = tuple(animals_list)

print(‘animals_list is {}.’.format(type(animals_list)))

print(‘animals_tuple is {}.’.format(type(animals_tuple)))

Output:

Code Listing 216

months_of_the_year_tuple is <class ‘tuple’>.

Months_of_the_year_list is <class ‘list’>.

Animals_list is <class ‘list’>.

Animals_tuple is <class ‘tuple’>

Looping through a Tuple

If you are looking to perform a particular action on every item within a tuple, use a for loop. The pattern is for item_variable in tuple_name followed by a code block.

Code Listing 217

months_of_the_year = (‘January’, ‘February’, ‘March’, ‘April’, ‘May’, ‘June’, ‘July’, ‘August’, ‘September’, ‘October’, ‘November’, ‘December’)

for month in months_of_the_year:

    print(month)

Output:

Code Listing 218

January

February

March

April

May

June

July

August

September

October

November

December

Tuple Assignment

You can use tuples to assign values to multiple variables at the same time. In the following example, the variables jan, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, and dec are assigned the months of the year from the months_of_the_year tuple.

Code Listing 219

months_of_the_year = (‘January’, ‘February’, ‘March’, ‘April’, ‘May’, ‘June’, ‘July’, ‘August’, ‘September’, ‘October’, ‘November’, ‘December’)

(jan, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, dec) = months_of_the_year

print(jan)

print(dec)

Output:

Code Listing 220

January

December

It is also possible to use tuple assignment with lists.

Code Listing 221

contact_info = [‘555-0123’, ‘david@gmail.com’]

(phone, email) = contact_info

print(phone)

print(email)

Output:

Code Listing 222

Tuple assignment can also be used with functions as well. For example, you could create a function that returns a tuple and assigns those values to different variables.

The following example uses the built-in max() and min() functions. The max() built-in function will return the largest item that is passed to it. The min() built-in function will return the smallest item that is passed to it.

Code Listing 223

def high_and_low(numbers):

    “””Determine the highest and lowest number”””

    highest = max(numbers)

    lowest = min(numbers)

    return (highest, lowest)

lucky_numbers = [37, 71, 47, 13, 17, 67]

(highest, lowest) = high_and_low(lucky_numbers)

print(‘The highest number is: {}’.format(highest))

print(‘The lowest number is: {}’.format(lowest))

Output:

Code Listing 224

The highest number is:71

The lowest number is: 13

You can also use tuple assignment in a for loop. In the following example the contacts list is comprised of a series of tuples. Each time the for loop is performed the variables name and phone will be populated with the contents of a tuple from the contacts list.

Code Listing 225

contacts = [(‘David’, ‘555-0123’), (‘Tom’, ‘555-5678’)]

for (name, phone) in contacts:

    print(“{}’s phone number is {}.”.format(name, phone))

Output:

Code Listing 226

David’s phone number is 555-0123.

Tom’s phone number is 555-5678.

Review

A tuple is an immutable list, which means that once it has been defined the values in the tuple cannot be changed.

The del statement can be used to delete a tuple. Del tuple_name

It is possible to convert a tuple to a list using the list() built-in function.

Lists can also be converted to tuples by using the tuple() built-in function.

You can use tuple assignment to assign values to multiple variables at the same time. (var_1, var_N) = (value_1, value_N)

Tuple assignment can be used in for loops.

The max() built-in function will return the largest item that is passed to it.

The min() built-in function will return the smallest item that is passed to it.

Exercises

ZIP Codes

Try creating a list of cities that will include a series of tuples that contain both a city’s name and its ZIP code. Loop through the list and utilize tuple assignment. Assign one variable to denote the city name and another variable to represent the ZIP code. Display the city’s name and ZIP code to the screen.

Sample output:

Code Listing 227
 

The ZIP code for Short Hills, NJ is 07078.

The ZIP code for Fairfax Station, VA is 22039.

The ZIP code for Weston, CT is 06883.

The ZIP code for Great Falls, VA is 22066.

Solution

Code Listing 228
 

cities = [

    (‘Short Hills, NJ’, ‘07078’),

    (‘Fairfax Station, VA’, ‘22039’),

    (‘Weston, CT’, ‘06883’),

    (‘Great Falls, VA’, ‘22066’)

]

for (city, zip_code) in cities:

    print(‘The ZIP code for {} is {}.’.format(city, zip_code))

Resources

list() documentation: https://docs.python.org/3/library/functions.html#func-list

max() documentation: https://docs.python.org/3/library/functions.html#max

min() documentation: https://docs.python.org/3/library/functions.html#min

type() documentation: https://docs.python.org/3/library/functions.html#type

tuple() documentation: https://docs.python.org/3/library/functions.html#func-tuple

About the Author

Jason Cannon started his career as a Unix and Linux System Engineer in 1999. Since that time he has utilized his Linux skills at companies such as Xerox, UPS, Hewlett-Packard, and Amazon.com. Additionally, he has acted as a technical consultant and independent contractor for small businesses as well as Fortune 500 companies.

He enjoys teaching others how to use and exploit the power of open source software. Jason is the author of Command Line Kung Fu, Shell Scripting, and Linux for Beginners. He is also the founder of the Linux Training Academy where he blogs and teaches online video training courses.

Be the first to get updates