Using .append() With Arrays in Python
Now you’ve seen a rather thorough introduction to how
.append() is used with Python lists. Now you’ll explore other types that use
Many other structures in Python have an
.append() method. They can be from a wide variety of modules, some standard to Python, some written by others. You’ll finish up this course by seeing two of them, the array and the double-ended queue.
First, the array. The
array class from the
array.array, is another list-like structure, but it’s much more limited.
00:40 All of the elements must be of the same type, not mixed as you see in lists. And you can only use certain types, like integers, characters, decimal values—things that are considered simple types in the language C. Arrays do some things much more efficiently than lists, so if you’re working only with numeric data, you might consider an array instead of a list.
The initializer requires at least one argument. The
typecode indicates what type of data the list will contain:
"i" for an integer,
"f" for floating point, things like that.
And you can optionally specify with a second argument an initial collection of values for the array. It’s in the
array module, so you can import it from there.
Create a new integer array with initial values
3 and look at its representation. It displays itself with the type that it is and what the array currently looks like. You can inspect individual elements,
02:07 including using slices, and modify individual elements in place.
So, the third element in the array, at position
2, was changed from
4. As you saw, arrays support slicing, but they also support the
So you can take our previous array and append to it. Calling
.append() will add a fourth value. The last two values are now
4. You can do this again.
You can’t use
.append() to add more than one element,
with individual numbers, or even to try a smaller list. I guess I’m up to
7. It doesn’t like that either. But if you’re curious, arrays do support
03:51 Elements in an array must all be of the same type, so if I try to append a decimal to an integer array, I get an error saying that it was expecting an integer and didn’t get one.
04:11 On the other hand, you can append an integer to a decimal array since the integers can be cast to floats in C. So you can create a float array of decimal values
.append() with an integer argument.
And that integer will be cast to the decimal value
4.0 and then appended to the array. So the array is still an array of floats, it just took the integer, changed it by casting it to a float, and then appending it.
So, there’s a look at using
.append() with arrays in Python. Next, you’ll look at using
.append() with double-ended queues.
Become a Member to join the conversation.