How to print all the contents of a list in Python

Asked

Viewed 5,692 times

1

How do I print contents from a list? I want the output to look like this:

Indice: 0  1  2  ...
likes:  0  0  0 ...

A post is represented as an element of a list. The list index indicates the post number. For example, the first post (post number 1) corresponds to the list’s zero index (0).

I got this:

Indice: 1
likes:  0

But I couldn’t get it all. Below is the code:

postagem = []

print('1) Criar um post')
alternativa = int(input())
t = postagem.append(0)

if(alternativa == 1):

    if(len(postagem) < 1):
        postagem.append(0)
        print('Indice:', postagem.index(0))
        print('likes:', postagem[0])

    if(len(postagem) >= 1):
        postagem.append(0)
        print('Indice:', len(postagem) - 1)
        print('likes', postagem[1])
  • Explain why from the start 2 not show up in Indice: 0 1 3...

2 answers

4


A simple way to do this is:

postagens = [1, 0, 5, 9]

print('Índice:', *range(len(postagens)))
print('Likes: ', *postagens)

The asterisk serves to make the unpacking, that is, when making print(*lista) It’s like you do print(lista[0], lista[1], etc...). And how the print, by default, prints a space between arguments, you already get the desired output:

Índice: 0 1 2 3
Likes:  1 0 5 9

Another way is by using join:

postagens = [1, 0, 5, 9]
separador = ' '
print('Índice:', separador.join(map(str, range(len(postagens)))))
print('Likes: ', separador.join(map(str, postagens)))

I had to use map to turn numbers into strings, since the join error if elements are not strings. Output is the same.

If the list is empty, the program still prints "Index:" and "Likes:" (and prints nothing later, as there are no elements in the list). If you want to include a check to only print something if the list has elements:

if postagens: # se a lista não for vazia
    separador = ' '
    print('Índice:', separador.join(map(str, range(len(postagens)))))
    print('Likes: ', separador.join(map(str, postagens)))

if postagens checks if the list is not empty, since empty lists are considered False.

Also note that I changed the name of the list to postagens, because if it’s going to have multiple posts, it’s better that the name is plural to indicate what it actually has there. It might seem like a bit of a detail, but giving better names helps a lot when programming (although in this case, the name could be quantidades_likes or just likes, because that’s what it actually has there - it doesn’t have a post itself, but anyway).

The difference to the another answer is that there is included an extra space at the end of the string, which depending on the case may or may not make a difference (For this specific case, it seems not to do, but thinking more generally, the output of the program can be passed to another, who hopes that there is no more space, for example - even if it makes no difference to a simple exercise, get used to thinking about these details, because there are cases where an extra space at the end makes a difference yes).


Only one detail, if the values are greater than 10, the data will be misaligned. For example, if the list is [10, 2, 4335, 10000], the exit will be:

Índice: 0 1 2 3
Likes:  10 2 4335 10000

In this case, you can use the formatting options to align the items. For example, you can choose an arbitrary size (say, 7) and align the columns to occupy this size:

def formatar(valor):
    return f'{valor:>7}' # alinhar à direita, usando 7 posições

postagens = [10, 2, 4335, 10000]
if postagens:
    print('Índice:', ''.join(map(formatar, range(len(postagens)))))
    print('Likes: ', ''.join(map(formatar, postagens)))

The format >7 says to align to the right, occupying 7 positions (and unused positions to the left are completed with spaces). The result is:

Índice:       0      1      2      3
Likes:       10      2   4335  10000

Of course, if you have a number with more than 7 digits, there will be misalignment in the same way (and for small values, there seems to be a "waste" of space). In this case, a more general solution would be, for each value, to obtain the amount of spaces it occupies, and to use this amount to align:

def formatar(valor, tamanho):
    return f'{valor:>{tamanho}}'

postagens = [10, 2, 4335, 10000, 1, 2, 3, 4, 5, 6, 1, 2, 3, 0, 1111, 4]
if postagens:
    indices = []
    likes = []
    for i, p in enumerate(postagens):
        tamanho = max(len(str(i)), len(str(p))) + 2
        indices.append(formatar(i, tamanho))
        likes.append(formatar(p, tamanho))

    print('Índice:', ''.join(indices))
    print('Likes: ', ''.join(likes))

I used enumerate to go through the list and at the same time obtain the respective index of each element.

For the size, I used max to take the largest size between the index and the value (because the index can be 10 and the value 1, for example, and in this case I would need to use 2 spaces to align, so I need to know which of the two has the largest size). I added 2 to have two more spaces separating the values (if you want more space separating the elements, just add to the size).

The exit is:

Índice:    0  1     2      3  4  5  6  7  8  9  10  11  12  13    14  15
Likes:    10  2  4335  10000  1  2  3  4  5  6   1   2   3   0  1111   4

Another point is that this part of your code doesn’t make much sense:

if(len(postagem) < 1):
    postagem.append(0)
    print('Indice:', postagem.index(0))
    print('likes:', postagem[0])

I mean, if the list is empty, you insert an element into it, then look for its index with index (but since it only has one element, you know it’s zero) and also prints the first element (which you entered 2 lines before, so you already know it’s zero). In that case, you could just write the zero directly:

if postagens: # lista não está vazia
    ... imprime, escolhendo um dos métodos acima
else: # lista vazia
    print('Indice: 0')
    print('likes: 0')

Also note that in Python - unlike some other languages - you don’t need parentheses for the if.

3

To print all posts, just scroll through all the elements with a loop for, and you should use a range to print the contents.

To leave all posts on a single line, set a string with space (" ") as argument for the parameter end of function print, so that the function does not break line.

See below the code:

postagem = [3, 1, 7]

print("Índice:", end = " ")

for indice in range(len(postagem)):
    print(indice, end = " ")

print("\nLikes: ", end = " ")

for post in postagem:
    print(post, end = " ")

See online: https://repl.it/repls/LinedHealthyEnvironment


Two other even simpler ways that I confess to having forgotten and that is in the another answer, is using unpacking and the method join() string. In the form of unpacking, you use an asterisk (*) to pass each element of the list as argument to the function.

Soon each widget will be printed on the same line.

postagens = [3, 1, 7]

print('Índice:', *range(len(postagem)))
print('Likes: ', *postagem)

The other way is by using the method join which serves to join all the elements of an iterable within a string.

The problem is that this method does not separate the elements, so we need to use a function called map() to apply the formatting.

def formatar(elemento):
    return str(elemento) + " "

postagem = [3, 1, 7]

print("Índice:", "".join(map(formatar, range(len(postagem)))))
print("Likes: ", "".join(map(formatar, postagem)))

See online: https://repl.it/repls/AblePureMinimalsystem

One thing quite interesting this way above to print the posts, is that you can format each post by changing only the return function formatar. See below:

def formatar(elemento):
    return "| <" + str(elemento) + "> "

Browser other questions tagged

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