Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: efficient syntax for creating a list composed of strings

I am new to python and essentially trying to figure out the syntax that replicates this functionality: strings = ["foo", "bar", "apple"] with something similar to strings = [foo, bar, apple] so that I don't have to put quotes around all the entries. Thanks!

like image 686
Spencer Avatar asked Sep 06 '11 17:09

Spencer


People also ask

How do I make a list of all elements in a string Python?

To convert a list to a string, use Python List Comprehension and the join() function. The list comprehension will traverse the elements one by one, and the join() method will concatenate the list's elements into a new string and return it as output.

What is the syntax for a list in Python?

In Python, a list is created by placing elements inside square brackets [] , separated by commas. A list can have any number of items and they may be of different types (integer, float, string, etc.).


3 Answers

strings = "foo bar apple".split()
like image 184
utdemir Avatar answered Oct 14 '22 13:10

utdemir


strings = r"foo, bar, apple".split(", ")
like image 2
Mike Samuel Avatar answered Oct 14 '22 12:10

Mike Samuel


You could place all the strings in a text file, one string on each line. Then strings = list(open("datafile", "r")).

like image 1
wberry Avatar answered Oct 14 '22 13:10

wberry