For example, the list contains:
- 2 strings
- 1 int
- 1 bool
- 1 nested list
Example:
["string1", 34, True, "string2", [2,4,6]]
Question: How to find the index of those 2 strings in the list? (object-types in the list must be treated as unknown)
For example, the list contains:
Example:
["string1", 34, True, "string2", [2,4,6]]
Question: How to find the index of those 2 strings in the list? (object-types in the list must be treated as unknown)
Use isinstance()
:
my_list = [True, 10.8, [1,2,3], False, True, "Hello", 12, "Sbioer", 2.5]
for i, item in enumerate(my_list):
if isinstance(item, basestring):
print i
Output:
5
7
However, if you want to check for int
values, you will get bool-type item's indexes too because (quoting text from some other source):
It is perfectly logical, if you were around when the bool type was added to python (sometime around 2.2 or 2.3).
Prior to introduction of an actual bool type, 0 and 1 were the official representation for truth value, similar to C89. To avoid unnecessarily breaking non-ideal but working code, the new bool type needed to work just like 0 and 1. This goes beyond merely truth value, but all integral operations. No one would recommend using a boolean result in a numeric context, nor would most people recommend testing equality to determine truth value, no one wanted to find out the hard way just how much existing code is that way. Thus the decision to make True and False masquerade as 1 and 0, respectively. This is merely a historical artifact of the linguistic evolution.
So if you want to check for only int
values just:
my_list = [True, 10.8, [1,2,3], False, True, "Hello", 12, "Sbioer", 2.5]
for i, item in enumerate(my_list):
if isinstance(item, int) and not isinstance(item, bool):
print i
If your list is named s
, then the following will work:
[i for i in range(len(s)) if type(s[i]) == str]
If you want to handle unicode strings, then you can change it to:
[i for i in range(len(s)) if isinstance(s[i], basestring)]
You can use a combination of enumerate()
and isinstance()
to get the index of the string items:
l = [1, True, 'Hello', [1, 3, False, 'nested'], 'Bye']
for i, item in enumerate(l):
if isinstance(item, basestring): # Python 2. Use (str, bytes) instead of basestring for Python 3
print i
Produces this output:
2 4
Note that this does not descend into the nested list; you will want to use recursion to do that.
You could do this with type()
function. Have a try with the following code.
l = [1,'abc', 'def', [1,2,3], True]
ans = []
for i in range(len(l)):
if type(l[i]) == str:
ans.append(i)
print ans