3

I have this name list that i got online,the list is 200 names long,here is a sample of it that i have saved in a text file.

John
Noah
William
James
Logan
Benjamin
...

I want them to be a list of strings i.e

x=['John','Noah','William',...]

I searched for questions similar but didn't find exactly what i need, any help is much appreciated.

wishmaster
  • 1,355
  • 1
  • 6
  • 18

3 Answers3

2

If the input is a file you can do...

x = []
with open('file_name', 'r') as f:
    for line in f:
       x.append(line.strip())
The Pineapple
  • 557
  • 3
  • 16
1

Additionally to The Pineapple's answer, you can also do list comprehension:

with open('file_name', 'r') as f:
    x=[i.rstrip() for i in f]

Now:

print(x)

Is the 200 names in a list.

U12-Forward
  • 65,118
  • 12
  • 70
  • 89
0

If data is contained in a file

with open('file_name', 'r') as f:
    data=f.readlines() # this will be a list of names

OR

with open('file_name', 'r') as f:
        data=f.read().splitlines() # to remove the trailing '\n'
mad_
  • 7,844
  • 2
  • 22
  • 37