String lists. Python is often used to process textual data. With strings, and string lists, we store and can handle this data in an efficient way.
In string lists, we use the syntax for lists and that of strings together. Literals are often used in examples, but are less useful in real programs. We read in data from files.
Create string lists. This program creates 2 equivalent string lists. It then performs some simple operations on the lists, such as getting the length and looping.
Part 1 The list initializer syntax is used. We get the length of the list with len and can use a for-loop to iterate.
Part 2 The second section of this code example uses the list() built-in to create an empty list. Then it calls append() to add elements.
# Part 1: create a list of three strings.
strings = ["one", "two", "THREE"]
# ... Display length of list.
print(len(strings))
# ... Display all string elements in list.
for value in strings:
print(value)
# Part 2: create a string list and build it with append calls.
strings2 = list()
strings2.append("one")
strings2.append("two")
strings2.append("THREE")
# ... Display length and individual strings.
print(len(strings2))
for value in strings2:
print(value)3
one
two
THREE
3
one
two
THREE
Combine string lists. Two string lists can be combined with the plus operator. This is simpler than trying to loop and add individual elements with append().
left = ["cat", "dog"]
right = ["bird", "fish"]
# Add two string lists together.
result = left + right
# The four elements are now in one list.
print(result)['cat', 'dog', 'bird', 'fish']
Read lines into list. Please add a file to your computer in an accessible location. To add each line to a string list, we can use readlines. These are some details here.
# Open a file on the disk (please change the file path).
f = open(r"C:\files\gems.txt", "r")
# Create an empty list.
lines = []
# Convert lines into string list.
for line in f.readlines():
lines.append(line.rstrip())
# Display all elements.
for element in lines:
print("[" + element + "]")ruby
sapphire
diamond
emerald
topaz[ruby]
[sapphire]
[diamond]
[emerald]
[topaz]
Loop over 2 string lists. We can use two approaches to loop over two lists at once. We can iterate over a range of indexes with the range() built-in function.
And We can use zip(), another built-in, to enumerate the lists together without indexes.
left = ["blue", "red"]
right = ["navy", "crimson"]
# Loop over index range.
for i in range(0, len(left)):
print(left[i], "...", right[i])
print()
# Loop over string lists with zip.
for (left_part, right_part) in zip(left, right):
print(left_part, "...", right_part)blue ... navy
red ... crimson
blue ... navy
red ... crimson
Join and split strings. With these methods we can handle CSV files (comma-separated values). With join, we combine a string list into a single string separated with a comma char.
Info With split we separate apart a string. We divide based on a delimiter character—here we use a single comma.
items = ["one", "two", "ten", "eight"]
# Combine string list into a single string.
string_value = ",".join(items)
print(string_value)
# Separate string into a string list.
list_values = string_value.split(",")
print(list_values)one,two,ten,eight
['one', 'two', 'ten', 'eight']
Duplicates. Sometimes we want to remove duplicate elements from a list. If ordering is important, we may need a special method to avoid reordering elements. Here a set is useful.
Two-dimensional. A list can contain other lists. We can use this kind of data structure as a two-dimensional grid of elements. These are jagged. Sub-lists can vary in length.
A summary. Python strings, and string lists, are simple and clear to use. This is a common requirement in programs. We handle groups of textual data.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.