[Solved] Python – how to do operations on individual items in list or string [closed]


Just index the list/string. It’s the same kind of syntax for both lists and strings.

>>> s="abcdefg"
>>> s[0] + s[1] # This does the operation 'a' + 'b'
'ab'

Lists and strings are both sequence types in Python and sequences in Python are 0-indexed. This means the first item is at index 0, the second at index 1, etc.

Also note that when you want to store these values in a variable, the syntax in Python is not 'a' + 'b' = somevar. Instead, it is somevar="a" + 'b'. The item(s) you want to assign to should always be on the left hand side of the assignment operator. So if I wanted to store the result above I would just do:

>>> somevar = s[0] + s[1]

Then you could print the value of somevar to see that it indeed holds the result you computed.

>>> somevar
'ab'

1

solved Python – how to do operations on individual items in list or string [closed]