3.1.4.9 Lists - collections of data | list methods
Adding elements to a list: continued
You can start a list's life by making it empty (this is done with an empty pair of square brackets) and then adding new elements to it as needed.
Take a look at the snippet in the editor. Try to guess its output after the
for
loop execution. Run the program to check if you were right.
It'll be a sequence of consecutive integer numbers from
1
(you then add one to all the appended values) to 5
.
We've modified the snippet a bit:
myList = [] # creating an empty list
for i in range(5):
myList.insert(0, i + 1)
print(myList)
what will happen now? Run the program and check if this time you were right, too.
You should get the same sequence, but in reverse order (this is the merit of using the
insert()
method).
Comments
Post a Comment