Ways to Create Lists Of Strings In Python
Below, are the methods of Lists Of Strings In Python.
- Using Square Brackets
- Using list() Constructor
- Using List Comprehension
- Append Strings to an Empty List
Lists Of Strings Using Square Brackets
The most straightforward way to create a list of strings is by enclosing the strings in square brackets. Here’s an example:
Python3
# Using Square Brackets my_list = [ "apple" , "banana" , "cherry" , "date" ] print (my_list) |
['apple', 'banana', 'cherry', 'date']
Lists Of Strings Using the list() Constructor
The `list()` constructor can be used to create a list from an iterable, such as a string. Here’s an example:
Python3
# Using the list() Constructor my_string = "python" my_list = list (my_string) print (my_list) |
['p', 'y', 't', 'h', 'o', 'n']
Lists Of Strings Using List Comprehension
List comprehension is a concise way to create lists in Python. It allows you to create a list based on an existing iterable. Here’s an example:
Python3
# Using List Comprehension words = [ "hello" , "world" , "python" ] my_list = [word.upper() for word in words] print (my_list) |
['HELLO', 'WORLD', 'PYTHON']
Lists Of Strings Append Strings to an Empty List
We can create an empty list and then append strings to it using the append() method. Here’s an example:
Python3
# Appending Strings to an Empty List my_list = [] my_list.append( "blue" ) my_list.append( "green" ) my_list.append( "red" ) print (my_list) |
['blue', 'green', 'red']
Lists Of Strings In Python
Python, a versatile and widely used programming language, offers several ways to work with lists of strings. Lists are fundamental data structures that allow you to store and manipulate collections of items. In this article, we will explore different methods to create lists of strings in Python, providing code examples and their corresponding outputs.