Reputation: 117
I am a new Python programmer and trying some stuff out. I want to create a list of strings and loop through my list to check the size of each element, if the size is greater than 5, then I will change that string into an uppercase string. I am stuck on how to access that element. Below is some of the code that I have written. Thank you in advance!
lis = ['heeeeellllooo','world','low','higggghhh']
for elem in list:
if len(lis[elem]) > 5:
list[elem].upper()
Upvotes: 0
Views: 215
Reputation: 250961
use a list comprehension
with ternary operator
:
In [16]: lis = ['heeeeellllooo','world','low','higggghhh']
In [17]: [x.upper() if len(x)>5 else x for x in lis] # this is a new list
Out[17]: ['HEEEEELLLLOOO', 'world', 'low', 'HIGGGGHHH']
You can also use enumerate()
, enumerate
returns a tuple
whole first item is the index of the element and the second item is the element itself.
This method modifies the original list.
In [18]: for index,elem in enumerate(lis):
....: if len(elem)>5:
....: lis[index]=elem.upper() #access element by index
....:
In [19]: lis
Out[19]: ['HEEEEELLLLOOO', 'world', 'low', 'HIGGGGHHH']
Python’s lists are really variable-length arrays, not Lisp-style linked lists. The implementation uses a contiguous array of references to other objects, and keeps a pointer to this array and the array’s length in a list head structure.
This makes indexing a list a[i] an operation whose cost is independent of the size of the list or the value of the index.
When items are appended or inserted, the array of references is resized. Some cleverness is applied to improve the performance of appending items repeatedly; when the array must be grown, some extra space is allocated so the next few times don’t require an actual resize.
Upvotes: 5
Reputation: 11686
Here is the correct way to do what you were trying using a for loop. Your code used two different variable names for the list: lis and list. The variable elem is the item in the list, not the index. To get the index, you need to use enumerate(). The solution shown by Ashwini Chaudhary is called a list comprehension and is a much better way to do this.
for i, elem in enumerate(lis):
if len(elem) > 5:
lis[i] = elem.upper()
Upvotes: 0
Reputation: 12806
enumerate
is very useful, if you'd like to change it in place.
Try this:
for idx, elem in enumerate(lis):
if len(elem) > 5:
list[idx] = elem.upper()
Upvotes: 3