Python lists

Python logo

Lists are part of the predefined types of Python, also called sequences are ordered, iterable, mutable elements. In the language ecosystem they play an extremely important role, and having a good knowledge of them and knowing how to handle them with skill and of fundamental importance on the part of the developer.

A list is nothing more than a container containing a series of values that can be of the same type or of different types. Types can be strings, integers, other lists, floating point numbers, Booleans, or dictionaries. Lists are elements ordered by an index that distinguishes them and gives their position, the wording of the indices follows the English notation so it starts from zero, this means that in an example:

list = ["a", "b", "c", "d"]

The newly composed list will be ordered in the first position with the element of value “a” which will have index equal to 0, the second element “b” will have index 1, the third “c” will have index 2, and the fourth will have index 3 , it follows that this list is made up of 4 elements (in this case all strings) which are ordered in sequence with indices ranging from 0 to 3.

The lists are mutable elements, therefore it is possible to carry out operations of modification, cancellation, copy, extension etc …
They are elements stored in memory for reference, and are composed of a set of values identified with a label called the name of the list.
Let’s see now how to define a list:
Note: In the following examples in some cases, when printing some elements on the screen, the print () function has been omitted, this is because the scripts have been executed from the Python shell so they do not necessarily need to be used. If these scripts are to be tested in .py files then it will be up to the user to add it.

* list example
list = ["a", 1, 1.5 ,[1, 2, "one"], True, {"name" : "Pippo", "surname" : "Verdi"}]

Above a list with heterogeneous values has been created, where the element to the left of the equal symbol is the name, and those to the right of the equal symbol are the values that must be enclosed in square brackets.

list = []
* example of an empty list

Here we have simply defined an empty List, this term is also used to empty it of all elements.

* I create a list
list = [1, 2, 44, 66, 3]
* I empty the list
list = []

Methods for managing lists.

Let’s now look at some methods for performing list operations.

append() Used to add items to the end of a list.

colors = ['green', 'white', 'red']
* the output of the list will be ['green', 'white', 'red']
* I add an element
colors.append("light blue")
* the output will be ['green', 'white', 'red', 'light blue']

clear() Used to remove all items from the list.

colors.clear()
* the output will be an empty list []

count Returns the number of elements contained in a list.

colors = ['green', 'white', 'red']
colors.count()
* the output will be 3

extend Add a list to another list.

colors1 = ['yellow', 'pink', 'black']
colors.extend(colors1)
* the output will be ['green', 'white', 'red', 'yellow', 'pink', 'black']

sort Used to sort the elements of a list in ascending order.

colors.sort()
* the output will be ['white', 'yellow', 'black', 'pink', 'red', 'green']

reverse Used to reverse a list from the end to the beginning.

colors.reverse()
* the output will be ['green', 'red', 'pink', 'black', 'yellow', 'white']

copy() Return a copy of the list.

copy_of_colors = colors.copy()

pop() Deletes an element indicated with the index, in the case of pop () you can enclose the deleted value in a variable.

colorS.pop(2)
* The value with index 2 which is equivalent to 'pink' has been removed.
x = colorS.pop(4)
* In this case the value with index 4 or the 'blank' has been eliminated and its value has been saved in the variable x

index Returns the index value of an element.

y = colors.index("black")
* the value of y is 2

remove() Removes an element based on its name.

colorS.remove('black')

insert() Insert an element at the given position.

colors.insert(2, 'violet')
* the result will be ['green', 'red', 'violet', 'yellow']

See the contents of a list

To see the contents of a list, simply type in its name.

numbers = [1, 2, 3, 4, 5, 6,7]
numers
* the result is the following [1, 2, 3, 4, 5, 6,7]

However, in order to see these elements in a more adequate formatting, or to be able to use certain logic in a program, it is necessary to iterate a list with a for () loop.

for i in numbers:
  print("this is the number: "+ str(i))

* Returns: 
* This is the number: 1
* This is the number: 2
* This is the number: 3
* This is the number: 4
* This is the number: 5
* This is the number: 6
* This is the number: 7

Other lists can be added to the lists which are called nested lists.

Engagedlist = [1, 2, 3, [45, 3, 12], "one", [10, "hello"]]

List values such as that for all Python variables are passed by reference, let’s take an example:

* If I create a list a
a = [1, 2, 3]
* Then I create a variable b which I assign you a
b = a
* The result of b will be [1, 2, 3]
* to a I add an element
a.append(4)
* The result of a will be [1, 2, 3, 4]
* But the result of b will also have become [1, 2, 3, 4]
* Then I add an element to b
b.append(5)
* The result of b will be [1, 2, 3, 4, 5]
* But the result of a will also have become [1, 2, 3, 4, 5]
* This means that a and b are two different names operating on the same memory address

To verify the previous example we can use the Python function id () which returns a unique identifying value corresponding to the address in memory of the variable and is valid for the entire life of it.

id(a)
* Returns in the case of my program 140263090601088
id(b)
* Returns in the case of my program 140263090601088

As you can see, lists a and b have the same memory identifier. Let’s now take another example to better understand the reference of variables.

c = ['a', 'b', 'c', 'd']
id(c) 
* Returns in my case 140263090507392
* If I now change the value of c to another value.
c = ["hello", "world"]
id(c)
* Returns in my case 140263090606272 

It should be noted that the identifier on the narrow variable in the two cases changes, this means that in reality it is not the same variable but they are two different memory allocations, in short, the name of the first variable has been taken and it has been assigned then at the second, the first variable is left in memory without a label and will remain there until Python decides to destroy it.

Small example of a program with lists

Let’s now take a small simple example of a small program that will ask us to enter a number and check its presence in a list.

* I create a list of numbers
list = [3, 55, 2, 34, 12, 88, 1, 76, 4, 28, 43]

* I use this variable to confirm the verification
verify = False

* I require a number
number = int(input("Please enter a number: "))

for i in list: 
  if i == number:
    verify = True

if verify == True:
  print("The number you entered is in the list")
else:
  print("The number you entered is NOT in the list")

This article has been made an overview on the use of lists, finally recalling the extreme importance they have in the Python world.

 

SviluppoMania
Stay Tuned

MARCO.VERGNANI

Nella mia vita a 12 anni e' entrato a far parte un Intel 80286 con 4MB di RAM, un Hard disk da 20 MB e una primissima scheda VGA appena uscita e da allora mi si e' aperto un mondo pieno di bit. Appassionato di programmazione fin da piccolo, mi diverto a costruire piccoli robottini. Curioso delle molteplici applicazioni che le macchine automatiche possono compiere, e adoro vedere volare quegli strani oggetti chiamati droni.

Related Posts

This site uses Akismet to reduce spam. Learn how your comment data is processed.