Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Use the built in <code>isinstance</code> and <code>all</code> functions, along with list slicing.</p> <pre><code>if all(isinstance(i, int) for i in mylist[-3:]): # do something else: # do something else </code></pre> <ul> <li><code>all</code> checks if all elements in the given iterable evaluate to <code>True</code>.</li> <li><code>isinstance</code> checks if the given object is an instance of the second parameter</li> <li><code>mylist[-3:]</code> returns the last three elements of <code>mylist</code></li> </ul> <p>Also, if you're using Python 2 and have very large numbers in your list, check for the <code>long</code> (long integer) type as well.</p> <pre><code>if all(isinstance(i, (int, long)) for i in mylist[-3:]): pass </code></pre> <p>This prevents numbers like <code>10**100</code> from breaking the condition.</p> <p>If, however, your last three elements are strings, you have two options.</p> <p>If you know none of the numbers are exceedingly large, you can use the <code>isdigit</code> string method.</p> <pre><code>if all(i.isdigit() for i in mylist[-3:]): pass </code></pre> <p>However, if they can be very large (around or over <code>2**31</code>), use a <code>try/except</code> block and the built in <code>map</code> function.</p> <pre><code>try: mylist[-3:] = map(int, mylist[-3:]) # do stuff except ValueError: pass </code></pre> <ul> <li><code>try</code> defines the block of code to execute</li> <li><code>except Exception</code> catches the given exception and handles it without raising an error (unless told to do so)</li> <li><code>map</code> applies a function to each element of an iterable and returns the result.</li> </ul>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload