+ 2
List in python
How do i get rid of this error? name = ["kent", "bryan", "destiney"] print(name.index("bryan")) //Output: 1 name = ["kent", ["bryan", "xvcb123" ], "destiny"] print(name.index("bryan")) Output// not in the list blah blah blah Hoooow?
7 ответов
+ 1
name=["kent",["bryan","xvcb123"],"destiny"]
for i,lst in enumerate(name):
for j,names in enumerate(lst):
if names == "bryan":
print(i, j)
name is the list and names is the variable.
This is one more easy of doing what you asked.
The first for loop has two variables i, lst . 'i ' will iterate in the list name which has length 3. 'lst' will iterate in the each i finding the value itself(like if you were finding kent it would be available at index 0 so we could have easily matched by using if lst=="kent".
The second for loop now also has two variables j,names. 'j' will iterate
in the each 'i' searching if it has another list in list. if it doesn't then it will iterate in the value itself(like for kent it will iterate at 0 its 'k ',at 1 its 'e' and so on...)
The 'names' variable will iterate in the list of list and search for bryan.
so when the i=1 and j=0 it will find and will print the i, j value.
If you still find it difficult, no worries post back.
0
Finding index in list of list doesn't work by in built index method
You have to use for loop like
For i,names in enumerate(name):
if bryan in name:
#ask your code to do
0
I don't understand, can u explain it one by one. Im still a newbie.
If i loop the name it shows the whole list, not one by one.
0
The enumerate is an in-built function which returns index and the value at index.
0
Okay, i got it now. Thank you guys
- 1
name.index("bryan") will find index for value "bryan" only .. in the 2nd list ,it has "bryan" is in another inner list , not a single data..
name[1].index("bryan") will give you index 0.
(because value is in index 0 of value at outer list data at index 1.)
internally it will search like,
for i in len(name):
if name[i]=="bryan" : return i
else return -1