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,437
  • 1
  • 10
  • 19

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
  • 567
  • 4
  • 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.

U13-Forward
  • 69,221
  • 14
  • 89
  • 114
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_
  • 8,121
  • 2
  • 25
  • 40