Hi,

I am having some trouble using the int function on an element of a list. My code currently looks like this.

for j in range(int(L)):
         for k in range(int(Allele[j])):
              alleleslocus_j.insert(k,loci.readline())

where Allele is a list of length L inputted by the user. I am having problems with the second line. When I run the program I get the error ValueError: invalid literal for int() with base 10: '['. I think that something about calling from the list is interacting with the int() syntax. I am wondering what exactly the problem is and how would I deal with it. Thanks!

Elise

PS This is a python program but I am compiling it in Sage

Dani AI

Generated

Quick practical follow-up for future readers: the root cause in this thread was stray non-digit characters in a string that was being passed to int() (as discovered). Inspecting the raw values first, as suggested, helps—but it’s better to validate or parse the input before calling int() so conversions are predictable and errors are explicit.

If the input is a Python-style list literal (for example something read from a file that looks like [1, 2, 3]), prefer a safe parser and then convert to ints:

import ast

raw = "[1, 2, 3]"   # line from file or input
try:
    seq = ast.literal_eval(raw)
    seq = [int(x) for x in seq]
except (ValueError, SyntaxError, TypeError):
    seq = []  # handle malformed input

For free-form text (comma- or space-separated), split and validate tokens with a simple regex before converting:

import re

raw = "[1, 2, 3]"
tokens = re.split(r'[,\s]+', raw.strip('[] \n\t'))
ints = [int(t) for t in tokens if re.fullmatch(r'[+-]?\d+', t)]

Extra tips: use repr() when printing values to reveal hidden characters (whitespace, brackets, quotes). Avoid eval(); use ast.literal_eval() or json.loads() depending on format. Prefer small, explicit checks (regex or str.isdigit()/sign checks) and catch specific exceptions (ValueError) rather than silencing all errors. When iterating, enumerate() and converting values once (instead of repeated int() calls inside nested loops) keeps code clearer and faster.

Recommended Answers

All 2 Replies

The error is being raised because it is trying to find the integer value of the character '[', which is apparently part of your list. You could either put in a try/except statement to 'pass' when you run into those, or print out the contents of the list and manually remove bogus entries.

Just post back if you need help with any of that.

Thanks so much for your help! I figured out my problem (I accidentally added brackets at the beginning and end of my list). it's fixed now.

Elise

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.