am using nested lists with key to store tv channels' info, while the nested list works fin when using straight, but would cause an error if used as a parameter in a function here is sample of my code
print(get_List()[1]['name'])
---> output:
Harley Davidson Racing TV (720p) [Not 24/7]
calling it from function
def get_AllName(list):
channel_names = []
x=0
while x<len(list):
channel_names.append(list()[x]['name'])
x =1
return channel_names
print(get_AllName(get_List()))
I get this error TypeError: 'list' object is not callable
CodePudding user response:
list
, as a type, is actually a callable (contrary to what is suggested in the comments), and can be called as list()
- it just returns an empty list though. So list()[x]['name']
is effectively [][x]['name']
and since the first list is empty, there's nothing to be indexed with x
.
get_List()
apparently returns a list of dictionaries, so to get a list of names:
def get_names(xs):
return[x['name'] for x in xs]
print(get_names(get_List()))
Or, without the extra function:
print([x['name'] for x in get_List()])
CodePudding user response:
It is not a good idea to name variables with data types or special keywords.
Instead of a list
, try naming it as List
or whole_list
or something
.
Your code will convert to:
def get_AllName(whole_list):
channel_names = []
x=0
while x<len(whole_list):
channel_names.append(whole_list[x]['name'])
x =1
return channel_names
print(get_AllName(get_List()))