Limit VS Code python list print – vs code prints 1 million elements to the terminal

Question:

I have a (hopefully) relatively simple question. I had a python list with 1M+ elements, and I want to limit the elements that VS Code prints to the terminal.

I.e.: I have a python list called "firms_of_interest" that has 1 million firms. When I execute the code "firms_of_interest", VS code prints every single element of the list to the terminal.

How do I get it to only print approximately. 10 elements?

Thank you.

Asked By: TM091994

||

Answers:

You need to loop through the list and not print the whole list

thislist = ["apple", "banana", "cherry"]
x=2
for i in range(x):
  print(thislist[i]) 

Python – Loop Lists

Answered By: mendacium

Answer

  1. Simplest way would be to just use slicing:
    $> firms_of_interest[:2]  # print two first firms
    $> ['Apple', 'Google']
  1. Second simplest way would be to use pandas Series class. Class Series have very nice implementation of __repr__ function which by default truncates list in case it is too long.
    import pandas as pd
    firms_of_interest = pd.Series(firms_of_interest)
    $> firms_of_interest
    $> ['Apple', 'Google', ..., 'Microsoft']
  1. You can try somehow change __repr__ method of list class, though I would not recommend to do it. One of the ways how it could be done:
   class MyList(list):
       def __repr__(self):
           total = f' total elements: {len(self)}'
           return repr(self[:10]) + total  # print first ten elements or less

   $> firms_of_interest = MyList(firms_of_interest)
   $> firms_of_interest
   $> ['Apple', 'Google', 'Microsoft', ...] total elements: 1000000

Explanation of repr function

In order to know how to display any object in terminal "VSCode" (actually python’s shell) calls repr function on the object, which returns string representation of the object. Under the hood repr function calls a special object’s method __repr__.

Examples

    # Class with default __repr__ method
    class Bar:
        pass

    $> bar = Bar()
    $> bar 
    $> <__main__.Bar at 0x7f111cf89e20>  # default implementation of __repr__

    # Class with redefined __repr__ method
    class Foo:
        def __repr__(self):
            return 'I am object of class Foo'
    
    $> foo = Foo()
    $> foo
    $> I am object of class Foo

Seems that Python’s list class implements __repr__ function in a way that it prints all elements in it.

Answered By: MrPisarik
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.