Programação RPi Python 08: listas Python e matrizes de bytes

RPi Python 08 Programming: Python Lists and Byte Arrays

In the previous tutorial , we learned about the basic syntax and various elements of the Python language. Python offers six types of sequences: strings, bytes, byte arrays, range, tuples, and lists.

It is important to point out that strings, bytes, range and tuples are immutable sequences that cannot be modified once they are defined. You can only create or destroy these sequences. This leaves byte lists and arrays as the only mutable sequences.

Python also supports unordered collections such as sets, frozen sets, and dictionaries. Frozen sets are immutable and sets and dictionaries are mutable collections. Furthermore, user-defined data structures can be defined as classes and are always mutable.

Immutable sequences and collections are useful when certain data values ​​need to be used throughout the code. Mutable sequences and collections are useful in maintaining related data values ​​that can be grouped together for specific reasons. Since data values ​​in a mutable sequence/collection can be modified anywhere in the code, they are ideally used for data manipulation and processing. After all, in any program we are manipulating and processing data values.

Typically, we will use sequences or (unordered) collections of data values ​​in most applications. Therefore, it is essential to understand how data values ​​in these mutable sequences/collections can be modified and manipulated. Lists, byte arrays, sets, and dictionaries are available as mutable Python sequences/collections. Let's review each one.

Lists

Lists are a mutable ordered collection of items. The items in a list are arbitrary and can be of any type. A list is defined by a list constructor or by using a pair of square brackets ( ).

You can also add, remove and modify items from a list. These items can be accessed through integer keys or indexes. The key or index of items in a list starts from zero. Therefore, the first item has a key or index of 0. This means that if “x” is a list, its items can be accessed as x(y) where y is the key/index of the item being accessed. If a negative index is used, the item will be accessed from the end of the list rather than the beginning.

At the end of the list, indices start at -1.

For example:

X = (1, 2, 3, 4)
X(1) # Returns 2
X(-1) #Returns 4

One or more items in a list can be modified, individually or through a slice. To do this individually, access the list item as a target reference in a task or augmented task as follows:

X = (1, 2, 3, 4)
X(1) = 'one' # x = (1, 'one', 3, 4)
X(2) += 22 # x = (1, a, 25, 4)

When using an augmented assignment to modify a list item, the data type of the RHS expression must be the same as that of the items. Otherwise, the result will be a semantic error.

Multiple items in a list can also be modified together by using the slicing operator as a target reference in an assignment statement like this:

X = (1, 2, 3, 4)
X(1:3) = (22, 33) # x = (1, 22, 33, 4)

A slice x(a:b) will modify all items with an index between a and b-1 in the list “x”, but not “b”. The slice can be assigned to any iterable. If the slice is assigned to an iterable with fewer items than the slice, the unassigned items are removed from the list. If the slice is assigned to an iterable with more items than the slice, the extra items are appended after the last item in the slice.

Here is an example:

X = (1, 2, 3, 4)
X(1:3) = (22) # x = (1, 22, 4)
X = (1, 2, 3, 4)
X(1:3) = (22, 33, 44) # x = (1, 22, 33, 44, 4)

If an empty slice x(a:a) receives certain data values/objects, those values/objects will be appended before the item with index “a: in list “x”. Similarly, a slice can cover the entire list and rebind new values/objects to it using the expression x(:) as the target reference for list “x”.

Consider this example:

X = (1, 2, 3, 4)
X(1:1) = (22) # x = (1, 22, 2, 3, 4)
X = (1, 2, 3, 4)
X(:) = (22, 33, 44) # x = (22, 33, 44)

Any item or slice of items can be deleted from a list using the “del” statement. Here, a slicing operator can also use step to skip deleting items at a regular interval.

Here are some examples:

X = (1, 2, 3, 4, 5, 6, 7, 8, 9)
delX(8)#x = (1, 2, 3, 4, 5, 6, 7, 8)
delX(4:6) # x = (1, 2, 3, 4, 7, 8)
delX(4:) # x = (1, 2, 3, 4)
delX(::2) # x = (2, 4)

Lists have these methods:

These methods can be applied to lists using the list_name.method_name syntax. Here is an example:

x = ('lion', 'tiger')=
x.append('elephant') # x = ('lion', 'tiger', 'elephant')
x.insert(0, 'leopard') # x = ('leopard', 'tiger', 'elephant')
x.extend(('cat', 'snake')) # x = ('leopard', 'tiger', 'elephant', 'cat', 'snake')
x.remove('snake') # x = ('leopard', 'tiger', 'elephant', 'cat')
x.pop(0) # x = ('tiger', 'elephant', 'cat')
x.index('gato') # returns 2
y = x.copy #y = ('tiger', 'elephant', 'cat')
x.count('gato') # returns 1
x.count('lion') # returns 0
x.sort #x = ('cat', 'elephant', 'tiger')
def f(e):
return len(e)
x.sort(key = f) # x = ('cat', 'tiger', 'elephant')
x.reverse #x = ('elephant', tiger, 'cat')
of course #x =

These built-in functions accept lists as arguments:

A list can be passed as an argument to the len function to get the size of that list. Here is an example:

x = (1, 2, 3, 4)
len(x) #returns 4

This table summarizes common list operations using operators, statements, methods, or functions:

Strings, bytes and byte arrays

Strings are an immutable sequence of Unicode (Python V3) or ASCII (Python V2) characters. Bytes are an immutable sequence of bytes. Byte arrays are a mutable sequence of bytes.

Strings are defined as single, double, or triple quoted sequences of Unicode/ASCII characters. Any item in an iterable intended to be used as a string must be quoted. Otherwise, Python will treat it as an identifier and assume it is a reference.

Here is an example:

x = ('a', 'b', 'c')
a = 12
b = 10
c = 11
y = (a, b, c)
print(x) # Print ('a', 'b', 'c')
print(y) # Prints (12, 10, 11)

Strings are immutable sequences. This means that you cannot add, remove or modify any item (Unicode/ASCII character) from a string by accessing its index. So these are invalid statements:

x = “Python”
x(0) = “J” #INVALID
del x(0) #INVALID

However, it is possible to perform string manipulation using constructed methods, functions, and user-defined functions. Similar characters in a string object can be replaced using the replace function.

Check out this example:

x = 'PPython'
x = x.replace(“P”, “J”)
print (x)

Bytes are defined by the byte function or by prefixing “b” before a byte string. Bytes are also immutable sequences. You cannot add, remove, or modify bytes in a byte object by accessing them from its index. Here are valid examples of byte objects:

x = b“Python”
x = byte (“Python”)

Byte arrays are a mutable version of bytes. They can be set using the bytearray function. These are valid examples of bytes and byte arrays:

x = bytearray(“Python”, 'utf-8') #string defined as byte array
x = bytearray(b“Python”)
x = bytearray((1, 2, 3, 4, 5,))
x = bytearray # empty bytearray

If a string is defined as an array of bytes using the bytearray function, the string must be enclosed in quotation marks and the encoding must be passed as an argument. Unlike bytes, byte arrays are mutable, meaning that you can add, remove, or modify items (bytes) in a byte array by accessing them through their index.

However, items in a byte array can only be accessed through a slicing operator. This is an invalid example of modifying the byte array:

x = bytearray(b”Python”)
print (x)
x(0) = b”J” #INVALID
print (x)

Here is a valid example of modifying the byte array:

x = bytearray(b”Python”)
print(x) #returns bytearray(b'Python')
x(0:1) = b”J”
print(x) #returns bytearray(b'Jython')

The following example shows adding, removing, modifying, and appending bytes in a byte array:

x = bytearray(b”Python”)
print (x)
x(6:) = b” is fun” #adding items to byte array by assignment
print(x) #prints bytearray(b'Python is fun')
x.append(110) #appending items to byte array
x.append(121)
print(x) #prints bytearray(b'Python is funny')
x(6 🙂 =b”” #removing items in byte array by assignment
print(x) #prints bytearray(b'Python is funny')
x(6:) = b”Objects”
print(x) #prints bytearray(b'Python Objects')
del x(6:) #removing items in byte array by del instruction
print(x) #prints bytearray(b'Python')

Be sure to test all of these example codes on your Raspberry Pi.

In the next tutorial we will discuss how to manipulate data values ​​in sets and dictionaries.

Conteúdo Relacionado

A network of sensors is embedded in every vehicle,...
The motor controller is one of the most important...
ESP32-CAM is a compact camera module that combines the...
A evolução dos padrões USB foi fundamental para moldar...
A SCHURTER anuncia um aprimoramento para sua conhecida série...
A Sealevel Systems anuncia o lançamento da Interface Serial...
A STMicroelectronics introduziu Diodos retificadores Schottky de trincheira de...
Determinar uma localização precisa é necessário em várias indústrias...
O novo VIPerGaN50 da STMicroelectronics simplifica a construção de...
A Samsung Electronics, fornecedora de tecnologia de memória avançada,...
O mercado embarcado tem uma necessidade de soluções de...
You have probably come across the term ' drag...
You probably have a support insulator if you've noticed...
You've probably seen stand an insulator sit on power...
You've probably seen shackle insulators enthroned on electricity poles,...
You have probably experienced situations where controlling a circuit...
Back to blog

Leave a comment

Please note, comments need to be approved before they are published.