Vectors in Python

2

Very well, I come from C-thread, and I'm having a hard time creating vectors in python. In C if I wrote vet = [5]; I would create a vector called vet with 5 indices. I wanted to know how to do this in python but I'm a beginner and I can not do it. The point is, how do I determine how many indexes my vector will have?

    
asked by anonymous 06.05.2017 / 04:23

2 answers

4

The short answer is: it does not define. Python is a high-level programming language and dynamic typing, you do not have to limit the size of your vector.

Incidentally, the Python type that most closely resembles the C vector is list . To set a new list , just do:

>>> meuVetor = []

You can confirm the type of the variable by doing:

>>> print(type(meuVetor))
<class 'list'>

At this point it is interesting to remember that everything in Python is an object, so even if the type list is native, it is a class. You can check all vector methods using the dir function:

>>> print(dir(meuVetor))
[..., 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

You can enter new values into the vector using the append method:

>>> meuVetor.append(1)
>>> print(meuVetor)
[1]
>>> meuVetor.append(2)
>>> print(meuVetor)
[1, 2]

Theoretically you can do this indefinitely. The size of the vector will vary according to its use. Grows and decreases on demand.

To access the elements, it is very similar to C:

>>> print(meuVetor[0])
1
>>> print(meuVetor[1])
2

You can initialize the vector with a predefined number of elements:

>>> meuVetor = [0]*5
>>> print(meuVetor)
[0, 0, 0, 0, 0]

But this is often unnecessary in more basic applications.

To go through all elements of the vector, just use for :

>>> for(valor in meuVetor):
...     print(valor)
0
0
0
0
0

This will work regardless of the size of the vector.

If you need to check the size of your vector at some point, you can use the len function:

>>> print(len(meuVetor))
5
>>> print(len([0] * 10))
10
  

For future references, while reading the documentation, keep in mind that list type is changeable.

    
06.05.2017 / 05:06
0

Python works with lists :

lista = [1, 2, 3]

Which are variants of size and type , regardless. Unlike the Array of some other languages.

If you want to create a list with a predefined number of elements, in addition to the assignment, you can do:

lista = [None]*n

Being n the number of elements. None is the empty object.

In python2, you can also use range() , which creates a numeric sequence in list form. However, in python3, this same range() is just an object iterable usually traversed by a for , not a list.

    
06.05.2017 / 04:54