Python Tutorial - Python Sequence Introduction

Python Exercise Lists

What is Sequence in Python?

The so-called sequence refers to a continuous memory space that can store multiple values. These values are arranged in a certain order. They can be accessed through the number (called the index) where each value is located.

In order to better understand the sequence, you can think of it as a hotel, so each room in the store is like a memory space for the sequence storage data, and the unique room number of each room is equivalent to the index value. In other words, through the room number (index), we can find each room (memory space) in this hotel (sequence).

In Python, sequence types include strings, lists, tuples, collections, and dictionaries. These sequences support the following general operations, but more specifically, collections and dictionaries do not support indexing, slicing, addition, and multiplication operations.

Strings are also a common sequence, and it is also possible to access the characters within a string directly through an index.

Python - Sequence Index

Each element in the sequence has its own number (index). Starting from the starting element, the index value is incremented from 0.

In addition, Python also supports negative index values. Such indexes are counted from right to left, in other words, counting from the last element, starting from the index value -1.

Note that when using a negative value as the index value of each element in the column order, it starts from -1 instead of 0.

You can access any element in a sequence, whether it is a positive or negative index value. Take the string as an example, to access the first and last elements of the "Python language website", you can use the following code:

Example:

str = "Python language website"
print (str [0], "==", str [-6])
print (str [5], "==", str [-1])
           

The output is:

P == e
n == e

Python - Sequence Slicing

The slicing operation is another way to access the elements in the sequence. It can access the elements in a certain range. Through the slicing operation, a new sequence can be generated.

The syntax for slicing a sequence is as follows:

sname[start : end : step]

The meaning of each parameter is:

  • sname: the name of the sequence;
  • start: indicates the start index position (including the position) of the slice. This parameter can also be left unspecified and will default to 0, that is, slice from the beginning of the sequence;
  • end: indicates the end index position of the slice (excluding this position), if not specified, the default is the length of the sequence;
  • step: indicates that in the slicing process, the elements are fetched once every few storage locations (including the current position), that is, if the value of step is greater than 1, the elements will be "jumped" when the slice is deserialized . If the value of step is omitted, the last colon can be omitted.

For example, slice the string "Python language website":

str = "Python language website"
#Take a string whose index range is between [0,2] (excluding the character at index 2)
print (str [: 2])
#Take 1 character every 1 character, the interval is the entire string
print (str [:: 2])
#Take the entire string, only a colon in []
print (str [:])
           

The output is:

Py
Pto agaewbie
Python language website

Python - Sequence Addition

In Python, two types of sequences are supported for addition using the "+" operator, which will concatenate two sequences without removing duplicate elements.

The "same type" mentioned here means that the sequences on both sides of the "+" operator are either sequence types, tuple types, or both strings.

For example, we have implemented concatenating 2 (or even multiple) strings with the "+" operator as follows:

str = "Python language website"
print ("Python language " + "Website: " + str)
           

The output is:

Python language Website: Python language website

Python - Sequence Multiplication

In Python, multiplying a sequence by the number n produces a new sequence whose contents are the result of the original sequence being repeated n times. Example:

str = "Python language website"
print(str*3)
           

The output is:

Python language websitePython language websitePython language website

What is special is that the list type can also implement the function of initializing a list of a specified length when performing a multiplication operation. For example, the following code will create a list of length 5, each element in the list is None, which means nothing.

# Use [] to create the list
list = [None] * 5
print (list)
           

The output is:

[None, None, None, None, None]

Check if element is included in sequence

In Python, you can use the in keyword to check whether an element is a member of a sequence. Its syntax is:

value in sequence

Where value represents the element to be checked and sequence represents the specified sequence.

For example, to check if the character 'e' is contained in the string "www.freelearningpoints.com", you can execute the following code:

str = "www.freelearningpoints.com"
print ("e" in str)
           

The output is:

True

Same usage as the in keyword, but with the opposite function. There is also the not in keyword, which checks whether an element is not included in the specified sequence. For example:

str = "www.freelearningpoints.com"
print ("e" not in str)
           

The output is:

False

Python - Built-in functions related to sequences

Python provides several built-in functions (shown in the following Table) that can be used to implement some common operations related to sequences.

Function Features
len() Calculate the length of a sequence, that is, how many elements are contained in the sequence.
max() Find the largest element in a sequence. Note that when using the sum () function on a sequence, the addition and addition operations must be all numbers, not characters or strings, otherwise the function will throw an exception, because the interpreter cannot determine that it is a concatenation operation (+ operator You can connect two sequences), or do the sum operation.
min() Find the smallest element in a sequence.
list() Convert sequence to list
str() Converts a sequence to a string.
sum() Calculate element sum.
sorted() Sort the elements.
reversed() Elements in reverse sequence.
enumerate() Combine sequences into an indexed sequence, mostly used in a for loop.

Here are a few examples for everyone:

str = "www.freelearningpoints.com"
#Find the largest characters
print (max (str))
#Find the smallest characters
print (min (str))
#Sorting elements in a string
print (sorted (str))
           

The output is:

w
.
['.', '.', 'a', 'c', 'e', 'e', 'e', 'f', 'g', 'i', 'i', 'l', 'm', 'n', 'n', 'n', 'o', 'o', 'p', 'r', 'r', 's', 't', 'w', 'w', 'w']

                               


More Tutorials:

Python Installation - Linux (Ubuntu)
Python Installation - Mac OS
Integrated Development Environment - IDE
Python - Basic Variables
Python - Sequence Introduction
Python - Output Formatting
Python - Escape Character
Python - Type Conversion
Python - Numbers
Python – Arithmetic Operators
Python – Assignment Operators
Python – Comparison Operators
Python – Logical Operators
Python – Precedence and Associativity Operators
Python – Bytes Type and Usage
Python – Long & Raw Strings
Python – Concatenate Function
Python – Slice Function
Python – Length and Split Function
Python – Join and Count Function
Python – Find Function
Python – Index Function
Python – Alignment Function
Python – Startswith and Endswith Function
Python – String Case Conversion
Python – Remove Specified Character
Python – Encode and Decode Function
Python – dir and help Function
Python – Input Output Introduction
Python – Basic Operation
Python – Open Function
Python – Read Function
Python – Readline Function
Python – Write Function
Python – Close Function
Python – Seek and Tell Function
Python – Pickle Module
Python - File Input Module and Linecache Module
Python - Pathlib Module
Python - Pathlib Module
Python - os.path Module
Python - fnmatch Module
Python - Tuple Introduction
Python - List Introduction
Python - List Add Element
Python - List Delete Element
Python - List Modification Element
Python - List Find Element
Python - Dictionary Introduction
Python - Dictionary Basic Operation
Python - Dictionary Method Guide
Python - Set Collection
Python - Set Basic Operation
Python - Set Basic Method
Python - Frozenset Method
Python - If Condition I
Python - If Condition II
Python - While loop
Python - For loop
Python - Pass Statement
Python - Break Statement
Python - Zip Reverse Function
Python - Function Introduction
Python - Positional Parameters
Python - Key Arguments
Python - None and Return
Python - Variable Scope
Python - Local Function
Python - Closure Method
Python - Lamdba Expression


More Python Exercises:

Python String Exercises
Python List Exercises
Python Library Exercises
Python Sets Exercises
Python Array Exercises
Python Condition Statement Exercises