-2

I am attempting to create a for loop to append both the contents of the first list num to num2 + the word thousand. I am looking for nums2 = ['one thousand', 'two thousand', 'three thousand', 'four thousand']. When I attempt to run this, all I am given is list indices must be integers or slices, not str. Any suggestions?

nums = ['one', 'two', 'three', 'four']
nums2 = []

for i in nums:
     nums2.append(nums[i] + ' thousand')

Edit (1:13PM EST, 12/10/2020):

This question has already been asked! My bad.
Appending the same string to a list of strings in Python

Gavin Wood
  • 11
  • 1
  • 3

4 Answers4

1

When you are iterating over the nums list, i is each value in the list; on the first iteration, i is equal to one, and on the second i is equal to two.

So when you are trying to access nums[i] you are trying to access nums["one"] (on the first iteration), which obviously doesn't exist.

To solve this, you can either change the for loop to an index based one, using range:

for i in range(len(nums)):
  nums2.append(nums[i] + ' thousand')

Or you could just stop trying to access the list from within the loop altogether, and use the value of i as the prefix to append thousand to:

for i in nums:
  nums2.append(i + ' thousand')
Random Davis
  • 6,662
  • 4
  • 14
  • 24
Alfie
  • 69
  • 1
  • 10
0

In this case "i" is a string since strings are the elements in the list. Try just using i instead of nums[i] in the append. Example:

nums = ['one', 'two', 'three', 'four']
nums2 = []

for i in nums:
     nums2.append(i + ' thousand')
0

the variable i in your for loop refer to the individual elements of the nums list, which in this case are strings. You need integers as indexes so in your case, the for loop can be modified as:

for i,k in enumerate(nums):
 nums2.append(nums[i] + ' thousand')

You can check if you got it right by printing nums2:

print(nums2)
0

You can try:

nums = ["Ford", "Volvo", "BMW"]
nums2 = []

for i in nums:
  nums2.append(i + ' thousand')
Mark
  • 74
  • 3