Python Forum
What a difference print() makes - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: What a difference print() makes (/thread-40956.html)



What a difference print() makes - Mark17 - Oct-19-2023

Hi all,

list1 = ["cat", "dog", "cat", "dog"]
list1.index("cat")
list1.count("dog")
If I enter that in a Jupyter Notebook cell then the output is: 2

list1 = ["cat", "dog", "cat", "dog"]
print(list1.index("cat"))
print(list1.count("dog"))
If I enter that in a Jupyter Notebook cell then the output is 0 with 2 on the very next line.

The .index() and .count() functions are being called in both programs but in the first, the second function return replaces the first function return. How would I explain this observation in pythonic terms?

Thanks!


RE: What a difference print() makes - deanhystad - Oct-19-2023

Great example here:

https://www.dataquest.io/blog/jupyter-notebook-tutorial/

Which says:
Quote:In general, the output of a cell comes from any text data specifically printed during the cell's execution, as well as the value of the last line in the cell, be it a lone variable, a function call, or something else.
If you ran this cell:
list1 = ["cat", "dog", "cat", "dog"]
print(list1.index("cat"))
print(list1.count("dog"))
f"It is raining {list1[0]}s and {list[1]}s"
The output would be
Output:
cat dog It is raining cats and dogs
The python interactive interpreter does something similar, but it automaticlly prints output at the end of each line, not each cell.
Output:
>>> print("spam") spam >>> print(["spam"] * 4) ['spam', 'spam', 'spam', 'spam'] >>> ", ".join(["spam"] * 4) 'spam, spam, spam, spam' >>>



RE: What a difference print() makes - DeaD_EyE - Oct-20-2023

As a side note, you could iterate over the enumerate(list1) and then you get (index, list_element).
list1 = ["cat", "dog", "cat", "dog"]


def get_all_indicies(iterable, item):
    for index, elemnt in enumerate(iterable):
        if item == elemnt:
            yield index


all_indicies = list(get_all_indicies(list1, "cat"))
Otherwise, you can use list1.index("item_to_find", START_INDEX).
list1 = ["cat", "dog", "cat", "dog"]


def get_all_indicies(list_like, item):
    index = 0

    while True:
        try:
            index = list_like.index(item, index)
            yield index
        except ValueError:
            return

        index += 1


list(get_all_indicies(list1, "cat"))