Python Programming - V. Sequences (List and Tuples) and Dictionaries

47 %
53 %
Information about Python Programming - V. Sequences (List and Tuples) and Dictionaries

Published on December 27, 2013

Author: ranelpadon



Feel free to download the material for offline viewing later, better images' resolutions, and crispier fonts.


PYTHON PROGRAMMING TOPICS I • Introduction to Python Programming II • Python Basics III • Controlling the Program Flow IV • Program Components: Functions, Classes, Packages, and Modules V • Sequences (List and Tuples), and Dictionaries VI • Object-Based Programming: Classes and Objects VII • Customizing Classes and Operator Overloading VIII • Object-Oriented Programming: Inheritance and Polymorphism IX • Randomization Algorithms X • Exception Handling and Assertions XI • String Manipulation and Regular Expressions XII • File Handling and Processing XIII • GUI Programming Using Tkinter

DATA STRUCTURES Data structures are structures that hold and organize data or information.

SEQUENCES Sequences, often called arrays in other languages, are data structures that store related data items.

SEQUENCES Python supports three basic sequence data types: a string, a tuple, and a list.

SEQUENCES A sequence element may be referenced by writing the sequence name followed by the element’s position number in square brackets ([ ]). The first element in a sequence is the zeroth element.



SEQUENCES Sequences can be accessed from the end of the sequence by using negative subscripts.

SEQUENCES Some types of sequences are immutable, that is, the sequence cannot be altered (e.g., changing the value of one of its elements). Python strings and tuples are immutable sequences. In other words, they are Read-Only.


SEQUENCES Python’s Tuple data structure is similar to Java’s native array and C’s native array, both of which have fixed length.

SEQUENCES Some sequences are mutable or can be altered. Python lists are mutable sequences. In other words, they are Read/Write data structure.


SEQUENCES Python’s List data structure is analogous to Java’s ArrayList and Vector classes, both of which are extendable.

SEQUENCES The length of the sequence is determined by the function call len(sequence ). This is useful when traversing the sequence.

SEQUENCES | len FUNCTION The length of the sequence is determined by the function call len(sequence ). This is useful when traversing the sequence.

SEQUENCES | len FUNCTION Same result with that of previous implementation, but more maintainable and scalable.




SEQUENCES | TUPLE | SINGLETON Tuple with single element must still include a comma. Parenthesis is optional in all type of Tuples, singleton or not.

SEQUENCES | TUPLE | (UN)PACKING Sequences can be unpacked, the values stored in the sequence are assigned to various identifiers. Unpacking is a useful programming shortcut for assigning values to multiple variables in a single statement.


SEQUENCES | TUPLE | (UN)PACKING Tuple packing/unpacking is useful when swapping variables.

SEQUENCES The += augmented assignment statement can insert a value in a list. When the value to the left of the += symbol is a sequence, the value to the right of the symbol must be a sequence also.



SEQUENCES Lists are not restricted to homogeneous data types. Python programmers typically use lists to store sequences of homogeneous values (values of the same data type)

SEQUENCES In general, a program uses a list to store homogeneous values for the purpose of looping over these values and performing the same operation on each value. Usually, the length of the list is not predetermined and may vary over the course of the program.

SEQUENCES The for/in structure iterates over a sequence. The for structure starts with the first element in the sequence, assigns the value of the first element to the control variable and executes the body of the for structure. Then, the for structure proceeds to the next element in the sequence and performs the same operations.



SEQUENCES Tuples store sequences of heterogeneous data. Each data piece in a tuple represents a part of the total information represented by the tuple. Usually, the length of the tuple is predetermined and does not change over the course of a program’s execution.


SEQUENCES | SLICING Python provides the slicing capability to obtain contiguous regions of a sequence. Slicing creates a new sequence; therefore, when a program passes a slice to a function, the original sequence is not affected.


SEQUENCES | SLICING is equivalent to the following expressions: sequence [ 0 : len( sequence ) ] sequence [ : len( sequence ) ] sequence [ 0 : ]

SEQUENCES Slicing creates a new sequence; therefore, when a program passes a slice to a function, the original sequence is not affected.

DICTIONARIES The dictionary is a mapping construct that consists of key-value pairs. Like a physical dictionary, it has listing of words and definitions. Dictionaries (called associative arrays in PHP hash maps/tables in Java, , and analogous to JavaScript Object Notation), can be thought of as unordered collections of values where each value is accessed through its corresponding key.

DICTIONARIES | EMPTY DICTIONARY To create an empty dictionary, use empty curly braces.

DICTIONARIES To create a dictionary with values, use a comma-separated sequence of key-value pairs, inside curly braces. Each key-value pair is of the form key : value.



DICTIONARIES Python dictionary keys must be immutable values, like strings, numbers or tuples, whose elements are immutable. Dictionary values can be of any Python data type.

DICTIONARIES | READ Dictionary values are accessed with the expression dictionaryName[ key ].

DICTIONARIES | READ Accessing a non-existent dictionary key causes the program to exit and to display a “key error” message. Use a fail-safe approach.

DICTIONARIES | WRITE To insert a new key-value pair in a dictionary, use the statement dictionaryName[ key ] = value.

DICTIONARIES | WRITE The statement dictionaryName [ key ] = value modifies the value associated with key, if the dictionary already contains that key. Otherwise, the statement inserts the key-value pair into the dictionary.

METHODS A method performs the behaviors (tasks) of an object. To invoke an object’s method, specify the name of the object, followed by the dot (.) access operator, followed by the method invocation.

METHODS | APPEND List method append adds an items to the end of a list.


METHODS | COUNT List method count takes a value as an argument and returns the number of elements in the list that have that value. If the list contains no elements with the specified value, method count returns 0.




METHODS | ITEMS, KEYS, VALUES Dictionary method items returns a list of tuples, where each tuple contains a key-value pair. Dictionary method keys returns an unordered list of the dictionary’s keys. Dictionary method values returns an unordered list of the dictionary’s values.







METHODS | COPY Dictionary method copy returns a new dictionary that is a shallow copy of the original dictionary. In a shallow copy, the elements in the new dictionary are references only to the elements in the original dictionary.

METHODS | DEEP COPY If the programmer wants to create a copy (called a deep copy), that is independent of the original dictionary, Python provides module copy. Function copy.deepcopy returns a deep copy of its argument.



PASS BY REFERENCE Python arguments are always passed by object reference, that is, the function receives references to the values passed as arguments.

PASS BY REFERENCE If a function receives a reference to a mutable object (e.g., a dictionary or a list), the function can modify the original value of the object. It is as if the object had been passed by reference.

PASS BY VALUE If a function receives a reference to an immutable object (e.g., a number, a string or a tuple whose elements are immutable values), the function cannot modify the original object directly. It is as if the object had been passed by value.

SEQUENCES AS ARGUMENTS To pass a list argument to a function, specify the name of the list without square brackets.


SEQUENCES | MULTI-DIMENSIONAL Sequences can contain elements that are also sequences. Such sequences have multiple subscripts. A common use of multiple-subscripted sequences is to represent tables of values consisting of in formation arranged in rows and columns.

SEQUENCES | MULTI-DIMENSIONAL To identify a particular table element, we must specify two subscripts: the first identifies the element’s row, the second identifies the element’s column.

SEQUENCES | MULTI-DIMENSIONAL Python does not support multiple-subscripted sequences directly, but allows programmers to specify single-subscripted tuples and lists whose elements are also single-subscripted tuples and lists, thus achieving the same effect.

SEQUENCES | MULTI-DIMENSIONAL The name of every element in a multiple-subscripted sequence is of the form a[ i ][ j ], where a is the name of the sequence, and i and j are the subscripts that uniquely identify the row and column of each element in the sequence.




SEQUENCES | MULTI-DIMENSIONAL Getting the sum of all elements in a 2-dimensional list. Useful for Reading values only.

SEQUENCES | MULTI-DIMENSIONAL Getting the sum of all elements in a 2-dimensional list using the indices/subscripts. Subscripts are useful also for overriding the array data.

SEQUENCES | MULTI-DIMENSIONAL To compute pure numerical problems (i.e., multi-dimensional arrays), You might want to use the NumPy (Numerical Python) package This package contains modules that handle arrays and provides multidimensional array objects for efficient computation.

PRACTICE EXERCISE Make a transpose function so that a given 2D list, say, Will be converted/transposed to this:

REFERENCES  Deitel, Deitel, Liperi, and Wiedermann - Python: How to Program (2001).  Disclaimer: Most of the images/information used here have no proper source citation, and I do not claim ownership of these either. I don’t want to reinvent the wheel, and I just want to reuse and reintegrate materials that I think are useful or cool, then present them in another light, form, or perspective. Moreover, the images/information here are mainly used for illustration/educational purposes only, in the spirit of openness of data, spreading light, and empowering people with knowledge. 

Add a comment

Related presentations

Presentación que realice en el Evento Nacional de Gobierno Abierto, realizado los ...

In this presentation we will describe our experience developing with a highly dyna...

Presentation to the LITA Forum 7th November 2014 Albuquerque, NM

Un recorrido por los cambios que nos generará el wearabletech en el futuro

Um paralelo entre as novidades & mercado em Wearable Computing e Tecnologias Assis...

Microsoft finally joins the smartwatch and fitness tracker game by introducing the...

Related pages

Python Programming/Sequences - Wikibooks, open books for ...

Python Programming/Sequences. ... There are three kinds of sequences in Python: ... (like list and tuple) nor to a key (like dictionary).
Read more

python - What's the difference between list and tuples ...

What's the difference between list and tuples? ... e.g. "Python Tuples are Not Just ... value or a tuple of values, and a list or other sequence is ...
Read more

Python List, Python Tuple, Python Dictionary

If a Python list were like a pencil, then a Python Tuple would be like a pen. Most programming languages include structures in which you can hold a ...
Read more

5. Data Structures — Python 2.7.11 documentation

... for all mutable data structures in Python. ... Sequence Types — str, unicode, list, tuple, ... a dictionary object returns a list of all the keys ...
Read more

Python Programming Tutorial - 9 - Sequences and Lists ...

... 9 - Sequences and Lists ... Python Programming Tutorial - 12 - More List Functions ... Lists, Tuples and Dictionaries - Duration: ...
Read more

python: list vs tuple, when to use each? - Stack Overflow

python: list vs tuple, ... Some tuples can be used as dictionary keys ... It is seldom just a tuple or list - more often it's sequence, ...
Read more - Lesson 6 - Tuples, Lists, and Dictionaries

The original python tutorial ... Tuples, Lists, and Dictionaries ... or entry in a list or dictionary ...
Read more

5. Data Structures — Python 3.3.6 documentation

Data Structures ¶ This chapter ... (see Sequence Types — list, tuple, range). ... Another useful data type built into Python is the dictionary ...
Read more

Let's Learn Python - Basics #2 of 8 - Strings, Lists ...

... in learning Python scripting/programming, ... Strings, Lists, Tuples and Dictionaries ... playlist?list... OBJECT ORIENTED PROGRAMMING ...
Read more