-3

I want to change an array from lower case to uppercase and print the result in Python.

In the following x will continue to print in lowercase.

x = ['ab', 'cd']
for i in x:
    i.upper()
print(x)

How do you write the code so x = ['AB', 'CD] when you print for x?

Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135

5 Answers5

3

You need to assign the uppercased characters back to the original string.

x = ['ab', 'cd']

#Loop through x and update element
for idx, item in enumerate(x):
    x[idx] = item.upper()

print(x)

Or by using list comprehension

x = ['ab', 'cd']
x = [item.upper() for item in x]
print(x)

The output will be

['AB', 'CD']
Devesh Kumar Singh
  • 20,259
  • 5
  • 21
  • 40
1

list comprehension is best for this.

x = ['ab', 'cd']
x = [i.upper() for i in x]
print(x)
mkrana
  • 422
  • 4
  • 10
0
x = ['ab', 'cd']
x = [i.upper() for i in x]

print(x)

output

['AB', 'CD']
sahasrara62
  • 10,069
  • 3
  • 29
  • 44
-1

Can be done with list comprehensions. These basically in the form of
[function-of-item for item in some-list]

in your case

x = [a,b,c] 
[i.upper() for i in x ]
abu
  • 11
  • 2
-2

If you don't know how to use list comprehension then you can write:

x = ['ab', 'cd']

result = [] # create list for upper strings

for i in x:
    upper_i = i.upper() # create upper string
    result.append(upper_i) # add upper string to list

x = result # replace lists

print(x)
furas
  • 134,197
  • 12
  • 106
  • 148
  • You can avoid the extra list by doing it in place! @furas – Devesh Kumar Singh May 03 '19 at 07:36
  • @DeveshKumarSingh I could avoid it but OP is beginner and I specially rewrite it in many steps. And probably OP choose my answer because it is not in one line. – furas May 03 '19 at 07:41
  • OP is already chosen your answer! I wonder the downvotes are due to the simplicity but extra usage of space @furas ! – Devesh Kumar Singh May 03 '19 at 07:43
  • 1
    @DeveshKumarSingh I think it is downvoted because of simplicity. But all these steps and even empty lines are to make it more useful for beginner. – furas May 03 '19 at 07:47