0% found this document useful (0 votes)
3 views

Python Tutorial_ Sequential Data Types

The document provides an overview of Python's sequential data types, including strings, lists, tuples, byte sequences, and range objects, highlighting their characteristics and usage. It explains how to access elements within these data types using indices and discusses the differences between mutable lists and immutable tuples. Additionally, it covers the concept of slicing for extracting parts of strings and lists, demonstrating with examples.

Uploaded by

Sentinel
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Python Tutorial_ Sequential Data Types

The document provides an overview of Python's sequential data types, including strings, lists, tuples, byte sequences, and range objects, highlighting their characteristics and usage. It explains how to access elements within these data types using indices and discusses the differences between mutable lists and immutable tuples. Additionally, it covers the concept of slicing for extracting parts of strings and lists, demonstrating with examples.

Uploaded by

Sentinel
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

Python Course

Home Python 2 Tutorial Python 3 Tutorial Advanced Topics Numerical Programming Machine Learning Tkinter Tutorial Contact

Previous Chapter: Operators


Next Chapter: List Manipulations

Sequential Data Types

Follow Bernd Klein,


the author of this
Python 3 Introduction website, at Google+:
Bernd Klein on
Tutorial Google
Sequences are one of the principal built-in data types besides numerics, mappings, files, instances and exceptions. Python provides for six sequence (or sequential) data
The Origins of types:
Bernd Klein on
Python Facebook
strings
Starting with
byte sequences
Python: The byte arrays
Interactive Shell lists Search this website:
Executing a tuples
Script range objects Go
Indentation
Strings, lists, tuples, bytes and range objects may look like utterly different things, but nevertheless they have some underlying concepts in common:
Data Types and This topic in German
Variables The items or elements of strings, lists and tuples are ordered in a defined sequence / Deutsche
Operators The elements can be accessed via indices Übersetzung:
Sequential Data Sequentielle
>>> text = "Lists and Strings can be accessed via indices!" Datentypen
Types: Lists and
>>> print(text[0], text[10], text[-1])
Strings L S !
Python 3
List >>>
Manipulations
Accessing lists: This is a tutorial in
Shallow and
Python3, but this
Deep Copy >>> lst = ["Vienna", "London", "Paris", "Berlin", "Zurich", "Hamburg"] chapter of our course
Dictionaries >>> print(lst[0]) is available in a
Sets and Frozen Vienna version for Python
>>> print(lst[2])
Sets 2.x as well:
Paris
An Extensive >>> print(lst[-1]) Sequential Data
Example Using Hamburg Types in Python 2.x
Sets >>>
input via the Classroom
keyboard Unlike other programming languages Python uses the same syntax and function names to work on sequential data types. For example, the length of a string, a list, and a tuple can be determined with a function Training
Conditional
called len(): Courses
Statements >>> countries = ["Germany","Switzerland","Austria","France","Belgium", "Netherlands", "England"]
The goal of this
Loops, while >>> len(countries)
7 website is to provide
Loop
>>> fib = [1,1,2,3,5,8,13,21,34,55] educational material,
For Loops >>> len(fib) allowing you to learn
Difference 10 Python on your own.
between >>> Nevertheless, it is
interators und faster and more
Iterables efficient to attend a
Output with Print "real" Python course
Formatted output in a classroom, with
Bytes an experienced
with string
trainer. So why not
modulo and the
The bytes object is a sequence of small integers. The elements of a byte object are in the range 0 through 255, corresponding to ASCII characters and they are printed as such. attend one of the live
format method Python courses in
Functions Strasbourg, Paris,
Recursion and Luxembourg,
Python Lists
Recursive Amsterdam, Zürich /
Functions Zurich, Vienna /
So far we had already used some lists, but we haven't introduced them properly. Lists are related to arrays of programming languages like C, C++ or Java, but Python lists are by far more flexible and powerful than
Parameter Wien, London, Berlin,
"classical" arrays. For example items in a list need not all have the same type. Furthermore lists can grow in a program run, while in C the size of an array has to be fixed at compile time.
Munich, Hamburg,
Passing in
Frankfurt, or Lake
Functions Generally speaking a list is an collection of objects. To be more precise: A list in Python is an ordered group of items or elements. It's important to notice that these list elements don't have to be of the same type.
Constance by Bernd
Namespaces It can be an arbitrary mixture of elements like numbers, strings, other lists and so on. The list type is essential for Python scripts and programs, this means that you will hardly find any serious Python code without
Klein, the author of
Global and Local a list.
this tutorial?
Variables
The main properties of Python lists:
Decorators
Memoization with They are ordered Onsite Training
Decorators The contain arbitrary objects Courses
Read and Write Elements of a list can be accessed by an index
Files They are arbitrarily nestable, i.e. they can contain other lists as sublists Let us come to your
Modular Variable size company or institute
They are mutable, i.e. the elements of a list can be changed and train your
Programming
employees, as we've
and Modules
done it many times in
Packages in List Notation and Examples
Amsterdam (The
Python List objects are enclosed by square brackets and separated by commas. The following table contains some examples of lists: Netherlands), Berlin
Regular (Germany), Bern
Expressions (Switzerland), Basel
List Description
Regular (Switzerland), Zurich
Expressions, [] An empty list (Switzerland),
Advanced [1,1,2,3,5,8] A list of integers Locarno
Lambda (Switzerland), Den
[42, "What's the question?", 3.1415] A list of mixed data Haag (The Hague),
Operator, Filter, types Hamburg (Germany),
Reduce and Map
["Stuttgart", "Freiburg", "München", "Nürnberg", "Würzburg", "Ulm","Friedrichshafen", Zürich", A list of Strings Frankfurt (Germany),
List Toronto (Canada),
"Wien"]
Comprehension Edmonton (Canada),
Iterators and [["London","England", 7556900], ["Paris","France",2193031], ["Bern", "Switzerland", 123466]] A nested list Munich (Germany),
Generators ["High up", ["further down", ["and down", ["deep down", "the answer", 42]]]] A deeply nested list Vienna / Wien
Exception (Austria) and many
Handling other cities. We do
Tests, DocTests,
Accessing List elements training courses in
England, Switzerland,
UnitTests Assigning a list to a variable:
Liechtenstein,
Object Oriented Austria, Germany,
languages = ["Python", "C", "C++", "Java", "Perl"]
Programming France, Belgium, the
Class and There are different ways of accessing the elements of a list. Most probably the easiest way for C programmers will be through indices, i.e. the numbers of the lists are enumerated starting with 0: Netherlands,
Instance Luxembourg, Poland,
Attributes >>> languages = ["Python", "C", "C++", "Java", "Perl"] UK, Italy and other
>>> print(languages[0] + " and " + languages[1] + " are quite different!") locations in Europe
Properties vs.
Python and C are quite different! and in Canada.
getters and >>> print("Accessing the last element of the list: " + languages[-1])
setters Accessing the last element of the list: Perl
>>> This way you will get
Inheritance
a perfect training up
Multiple to your needs and it
The previous example of a list has been a list with elements of equal data types. But as we had before, lists can have various data types. The next example shows this:
Inheritance will be extremely cost
Magic Methods group = ["Bob", 23, "George", 72, "Myriam", 29] efficient as well.
and Operator Contact us so we can
Overloading define and find the
OOP, Inheritance best course
curriculum to meet
Example
Sublists your needs, and
Slots
schedule course
Classes and sessions to be held at
Lists can have sublists as elements. These sublists may contain sublists as well, i.e. lists can be recursively constructed by sublist structures.
Class Creation your location.
Road to >>> person = [["Marc","Mayer"],["17, Oxford Str", "12345","London"],"07876-7876"]
Metaclasses >>> name = person[0]
Metaclasses >>> print(name)
['Marc', 'Mayer']
Skilled Python
Metaclass Use >>> first_name = person[0][0] Programmers
Case: Count >>> print(first_name)
Function Calls Marc You are looking for
>>> last_name = person[0][1] experienced Python
Abstract Classes
>>> print(last_name)
developers or
Mayer
programmers? We
Python >>> address = person[1]
>>> street = person[1][0] can help you, please
>>> print(street) contact us.
In Greek mythology,
17, Oxford Str
Python is the name
of a a huge serpent Quote of the
The next example shows a more complex list with a deeply structured list: Day:
and sometimes a
dragon. Python had >>> complex_list = [["a",["b",["c","x"]]]]
been killed by the >>> complex_list = [["a",["b",["c","x"]]],42] "Clearly,
god Apollo at Delphi. >>> complex_list[0][1] programming courses
Python was created ['b', ['c', 'x']] should teach
>>> complex_list[0][1][1][0] methods of design
out of the slime and
'c'
mud left after the and construction, and
great flood. He was the selected
appointed by Gaia examples should be
(Mother Earth) to such that a gradual
guard the oracle of development can be
Delphi, known as Tuples nicely
Pytho. demonstrated."
The programming A tuple is an immutable list, i.e. a tuple cannot be changed in any way once it has been created. A tuple is defined analogously to lists, except that the set of elements is enclosed in parentheses instead of square (Niklaus Wirth)
language Python has brackets. The rules for indices are the same as for lists. Once a tuple has been created, you can't add elements to a tuple or remove elements from a tuple.
not been created out
of slime and mud but Where is the benefit of tuples?
out of the
Tuples are faster than lists.
programming
If you know that some data doesn't have to be changed, you should use tuples instead of lists, because this protects your data against accidental changes. Data Protection
language ABC. It has
The main advantage of tuples consists in the fact that tuples can be used as keys in dictionaries, while lists can't. Declaration
been devised by a
Dutch programmer,
The following example shows how to define a tuple and how to access a tuple. Furthermore we can see that we raise an error, if we try to assign a new value to an element of a tuple:
named Guido van Data Protection
Rossum, in >>> t = ("tuples", "are", "immutable") Declaration
Amsterdam. >>> t[0]
'tuples'
>>> t[0]="assignments to elements are not possible"
Traceback (most recent call last):
Origins of File "<stdin>", line 1, in <module>
Python TypeError: 'tuple' object does not support item assignment

Guido van Rossum


wrote the following
about the origins of
Python in a foreword Slicing
for the book
"Programming
In many programming languages it can be quite tough to slice a part of a string and even tougher, if you like to address a "subarray". Python makes it very easy with its slice operator. Slicing is often implemented
Python" by Mark Lutz
in other languages as function with possible names like "substring", "gstr" or "substr".
in 1996:
"Over six years ago,
So every time you want to extract part of a string or a list, you use in Python the slice operator. The syntax is simple. Actually it looks a little bit like accessing a single element with an index, but instead of just one
in December 1989, I
number we have more, separated with a colon ":". We have a start and an end index, one or both of them may be missing. It's best to study the mode of operation of slice by having a look at examples:
was looking for a
"hobby"
>>> str = "Python is great"
programming project >>> first_six = str[0:6]
that would keep me >>> first_six
occupied during the 'Python'
week around >>> starting_at_five = str[5:]
Christmas. My office >>> starting_at_five
(a government-run 'n is great'
>>> a_copy = str[:]
research lab in
>>> without_last_five = str[0:-5]
Amsterdam) would >>> without_last_five
be closed, but I had a 'Python is '
home computer, and >>>
not much else on my
hands. I decided to Syntactically, there is no difference on lists. We will return to our previous example with European city names:
write an interpreter
for the new scripting >>> cities = ["Vienna", "London", "Paris", "Berlin", "Zurich", "Hamburg"]
language I had been >>> first_three = cities[0:3]
>>> # or easier:
thinking about lately:
...
a descendant of ABC >>> first_three = cities[:3]
that would appeal to >>> print(first_three)
Unix/C hackers. I ['Vienna', 'London', 'Paris']
chose Python as a
working title for the Now we extract all cities except the last two, i.e. "Zurich" and "Hamburg":
project, being in a
slightly irreverent >>> all_but_last_two = cities[:-2]
>>> print(all_but_last_two)
mood (and a big fan
['Vienna', 'London', 'Paris', 'Berlin']
of Monty Python's >>>
Flying Circus)."

Slicing works with three arguments as well. If the third argument is for example 3, only every third element of the list, string or tuple from the range of the first two arguments will be taken.

If s is a sequential data type, it works like this:

s[begin: end: step]

The resulting sequence consists of the following elements:

s[begin], s[begin + 1 * step], ... s[begin + i * step] for all (begin + i * step) < end.

In the following example we define a string and we print every third character of this string:

>>> str = "Python under Linux is great"


>>> str[::3]
'Ph d n e'

The following string, which looks like letter salad, contains two sentences. One of them contains covert advertising of my Python courses in Canada:

"TPoyrtohnotno ciosu rtshees lianr gTeosrto nCtiot yb yi nB oCdaennasdeao"

Try to figure it out using slicing with the step argument. The solution is: You have to set step to 2

>>> s
'TPoyrtohnotno ciosu rtshees lianr gTeosrto nCtiot yb yi nB oCdaennasdeao'
>>> s[::2]
'Toronto is the largest City in Canada'
>>> s[1::2]
'Python courses in Toronto by Bodenseo'
>>>

You may be interested in how we created the string. You have to understand list comprehension to understand the following:

>>> s = "Toronto is the largest City in Canada"


>>> t = "Python courses in Toronto by Bodenseo"
>>> s = "".join(["".join(x) for x in zip(s,t)])
>>> s
'TPoyrtohnotno ciosu rtshees lianr gTeosrto nCtiot yb yi nB oCdaennasdeao'
>>>

Length

The length of a sequence, i.e. a list, a string or a tuple, can be determined with the function len(). For strings it counts the number of characters and for lists or tuples the number of
elements are counted, whereas a sublist counts as 1 element.

>>> txt = "Hello World"


>>> len(txt)
11
>>> a = ["Swen", 45, 3.54, "Basel"]
>>> len(a)
4

Concatenation of Sequences

Combining two sequences like strings or lists is as easy as adding two numbers. Even the operator sign is the same.
The following example shows how to concatenate two strings into one:

>>> firstname = "Homer"


>>> surname = "Simpson"
>>> name = firstname + " " + surname
>>> print(name)
Homer Simpson
>>>

It's as simple for lists:

>>> colours1 = ["red", "green","blue"]


>>> colours2 = ["black", "white"]
>>> colours = colours1 + colours2
>>> print(colours)
['red', 'green', 'blue', 'black', 'white']

The augmented assignment "+=" which is well known for arithmetic assignments work for sequences as well.

s += t

is syntactically the same as:

s = s + t

But it is only syntactically the same. The implementation is different: In the first case the left side has to be evaluated only once. Augment assignments may be applied for mutable objects as an optimization.

Checking if an Element is Contained in List

It's easy to check, if an item is contained in a sequence. We can use the "in" or the "not in" operator for this purpose.
The following example shows how this operator can be applied:

>>> abc = ["a","b","c","d","e"]


>>> "a" in abc
True
>>> "a" not in abc
False
>>> "e" not in abc
False
>>> "f" not in abc
True
>>> str = "Python is easy!"
>>> "y" in str
True
>>> "x" in str
False
>>>

Repetitions

So far we had a "+" operator for sequences. There is a "*" operator available as well. Of course there is no "multiplication" between two sequences possible. "*" is defined for a sequence and an integer, i.e. s * n or
n * s.
It's a kind of abbreviation for an n-times concatenation, i.e.

str * 4

is the same as

str + str + str + str

Further examples:

>>> 3 * "xyz-"
'xyz-xyz-xyz-'
>>> "xyz-" * 3
'xyz-xyz-xyz-'
>>> 3 * ["a","b","c"]
['a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c']

The augmented assignment for "*" can be used as well:


s *= n is the same as s = s * n.

The Pitfalls of Repetitions

In our previous examples we applied the repetition operator on strings and flat lists. We can apply it to nested lists as well:

>>> x = ["a","b","c"]
>>> y = [x] * 4
>>> y
[['a', 'b', 'c'], ['a', 'b', 'c'], ['a', 'b', 'c'], ['a', 'b', 'c']]
>>> y[0][0] = "p"
>>> y
[['p', 'b', 'c'], ['p', 'b', 'c'], ['p', 'b', 'c'], ['p', 'b', 'c']]
>>>

This result is quite astonishing for beginners of Python programming. We have assigned a new value to the first element of the first sublist of y, i.e. y[0][0] and we have
"automatically" changed the first elements of all the sublists in y, i.e. y[1][0], y[2][0], y[3][0]

The reason is that the repetition operator "* 4" creates 4 references to the list x: and so it's clear that every element of y is changed, if we apply a new value to y[0][0].

Previous Chapter: Operators


Next Chapter: List Manipulations

© 2011 - 2018, Bernd Klein, Bodenseo; Design by Denise Mitchinson adapted for python-course.eu by Bernd Klein

You might also like