Access list element within Python list

Asked

Viewed 2,542 times

0

I have two lists within a list and each index of the list contains an ordered pair, in this way: [[2, 5], [3, 6], ..., [x, f(x)]].

I want to know how to access a specific item of one of the lists, because I only wanted to access the value x from the example I showed. Something like index.lista[x] in a given index.

4 answers

6


In Python list is a mutable and ordered collection whose access of the elements are done through an index, index whose numbering starts from zero.

Knowing this and that a nested list is nothing more than a list within another list, to access nested lists just access the desired element using two indexes. The first index to get the sub-list and second index to get the requested item.

#Define a função f(x)
def f(x):
  return x + 3

#Constroi a lista de pares ordenados [x,f(x)]
lista = [[x,f(x)] for x in range(2,10)]

#Imprime o x para o terceiro par ordenado
print(f'x = {lista[2][0]}')

#Imprime o f(x) para o terceiro par ordenado
print(f'f(x) = {lista[2][1]}')

Code in Repl.it: https://repl.it/repls/TerribleDroopyShareware

  • 1

    Affz, it was faster than I kkk When I was almost done answering appeared that you had already answered.

  • It worked out here, vlw!

1

I think you’re wanting something that gets x and returns the index in the list, but since x is inside another list needs a function:

def procura_lista(l, x):
    for posicao, valor in enumerate(l):
        if valor[0] == x:
            return posicao
    raise Exception("Nao encontrado")

This function receives the list and the value you want to look for in the first position of the sub-list. It returns the position where it was found and generates an exception if it has not been found. In the function, enumerate was used to create a pair position, value, where position is the index of the value in question.

For example:

>>> vv = [[1, 2], [3, 4], [6, 7]]
>>> procura_lista(vv, 1)
0
>>> procura_lista(vv, 3)
1
>>> procura_lista(vv, 6)
2
>>> print(vv[procura_lista(vv, 1)])
[1, 2]

1

In the same way that you access an element within one-dimensional, you also access it in a multidimensional list. To access an item within a list, you would write the following code:

lista[indice]

In doing so, you get the item that is in the position you specified. In the case of multidimensional lists, the values within them would be other lists, so you would get another list and with that you could do the same process to access the item. See below for an example:

lista1 = [1,2,3,4,5,6]                                               # Unidimensional
lista2 = [[1,2], [3,4], [5,6]]                                       # Bidimensional
lista3 = [[[1,2], [3,4], [5,6]], [["macarrão", "pizza", "salada"]]]  # Tridimensional

# Abaixo eu obtenho o valor 3 de todas as listas
#--------------------------------------------------

# Obtém o valor na posição 2 
lista1[2] 

# Obtém a lista "[3,4]" na posição 1 e depois obtém o valor na posição 0 dessa lista
lista2[1][0] 

# Obtém a lista "[[1,2], [3,4], [5,6]]" na posição 0 e realiza as mesmas etapas acima
lista3[0][1][0] 

Just like Augusto Varques said, you can create a list of ordered pairs using list comprehension, but I think this syntax is still a little difficult for you. So let’s uncomplicate that.

#Define a função f(x)
def f(x):
  return x + 3

#Constroi a lista de pares ordenados [x,f(x)]
lista = [[x,f(x)] for x in range(2,10)]

In the code above that Augusto made, the for loop traverses the values obtained by range moving them to the variable x. After that, this value is passed inside the list [x, f(x)] in the first position and is used as argument for the function f() to return its value added to 3. Finally, every loop of the loop for, a list is returned inside the "main".

It got hard, though ? Then see the code below that does the same thing of the above code only in a less compact way only easier to understand:

def criaPares(start = 2, end = 5):
    lista = []

    for x in range(start, end):
        lista.append( [x, x + 3 ] )
    return lista
  • It was my last vote of the day https://imgur.com/a/tb6VtSb

  • @Augustovasques kkkk arrived on time so xD

0

From what I understand you want to implement a script that is able to display only the first of the ordered pair contained in each sublists of a particular list.

Well, to implement a code that is able to accomplish such a task, you must be aware that you must iterate on the list outermost and also the more internal lists - the sublists.

To resolve this issue we can use the following code:

lista = [[2, 5], [3, 6], [4, 7], [5, 8]]

for lis in lista:
    for c in lis:
        if c == lis[0]:
            print(c)

Note that when we execute the following code the first time will begin to iterate on the most external list, that is, on the list called lista. Continuing the implementation, the second for will begin to iterate on each one internal lists - sub-lists - and, with the help of the block if will be verified if the value of the respective iteration belongs to the first element of the ordered pair - first element of the sublist, ie the element corresponding to the position lis[0]. If yes, it is displayed on the screen.

Note that the results of this code will be displayed in a column.

Now if you want to display these values on the same line, just use the following code:

lista = [[2, 5], [3, 6], [4, 7], [5, 8]]

for lis in lista:
    for c in lis:
        if c == lis[0]:
            print(c, end=' ')
print()

Note that these two codes is able to work with only one list, which is precisely the list I wrote inside the code.

Now imagine the following situation: "Create a list of 6 sublists, where each contains an ordered pair - (x, f(x)) - where "x" be an integer value and "f(x)" be the square of "x".

How could we resolve this situation?

To resolve this situation we must:

  1. Insert each of the 6 values - one at a time;
  2. Assemble the list containing the 6 sublists, each with their respective ordered pair;
  3. Display the list;
  4. Capture only the "x" components of each ordered pair and display them.

Following this logic we can use the following code:

# Primeiro bloco for:
lista = list()
for i in range(1, 7):
    par_ordenado = list()
    for j in range(1, 3):
        if j == 1:
            par_ordenado.append(int(input(f'Digite o valor do {i}º "X": ')))
        else:
            par_ordenado.append(par_ordenado[0] ** 2)
    lista.append(par_ordenado)
print(f'A lista montada é:\n{lista}')

# Segundo bloco for:
print('As componentes "x" do pares ordenados são:')
for lis in lista:
    for c in lis:
        if c == lis[0]:
            print(c, end=' ')
print()

Observing

If you want to display the "f(x)" components of for ordered, just go to 2nd block for and replace the command line...

if c == lis[0]

for...

if c == lis[1]

Browser other questions tagged

You are not signed in. Login or sign up in order to post.