C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Part A: The list initializer syntax is used. We get the length of the list with len and can use a for-loop to iterate.
Part B: The second section of this code example uses the list() built-in to create an empty list. Then it calls append() to add elements.
Python program that creates string lists
# Part A: create a list of three strings.
strings = ["one", "two", "THREE"]
# ... Display length of list.
print(len(strings))
# ... Display all string elements in list.
for st in strings:
print(st)
# Part B: 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 st in strings2:
print(st)
Output
3
one
two
THREE
3
one
two
THREE
Rstrip: Before we call append() on each string line, we use rstrip. This eliminates annoying trailing newlines.
StripContents, gems.txt: Python
ruby
sapphire
diamond
emerald
topaz
Python program that reads lines into string list
# 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 + "]")
Output
[ruby]
[sapphire]
[diamond]
[emerald]
[topaz]
Python program that combines string lists
left = ["cat", "dog"]
right = ["bird", "fish"]
# Add two string lists together.
result = left + right
# The four elements are now in one list.
print(result)
Output
['cat', 'dog', 'bird', 'fish']
Zip: We can use zip(), another built-in, to enumerate the lists together without indexes.
Python program that uses range, zip
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)
Output
blue ... navy
red ... crimson
blue ... navy
red ... crimson
Split: With split we separate apart a string. We divide based on a delimiter character—here we use a single comma.
Python program that uses join, split
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)
Output
one,two,ten,eight
['one', 'two', 'ten', 'eight']