What's the fastest way to convert a list into a python list?

Question:

Say I have a list like such:

1
2
3
abc

What’s the fastest way to convert this into python list syntax?

[1,2,3,"abc"]

The way I currently do it is to use regex in a text editor. I was looking for a way where I can just throw in my list and have it convert immediately.

Asked By: blahahaaahahaa

||

Answers:

Read the file, split into lines, convert each line if numeric.

# Read the file
with open("filename.txt") as f:
    text = f.read()

# Split into lines
lines = text.splitlines()

# Convert if numeric
def parse(line):
    try:
        return int(line)
    except ValueError:
        return line

lines = [parse(line) for line in lines]
Answered By: Mateen Ulhaq

If it’s in a text file like you mentioned in the comments then you can simply read it and split by a new line. For example, your code would be:

with open("FileName.txt", "r") as f:
    L = f.read().split("n")

print(L)

Where L is the list.

Now, if your looking for the variables to be of the correct type instead of all being strings, then you can loop through each in the list to check. For example, you could do the following:

for i in range(len(L)):
    if L[i].isnumeric():
        L[i] = int(L[i])
Answered By: Timmy Diehl
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.