Reputation: 240
Name_list = [
['Name 1', 'Name 2', 'Name 3']
]
Name = 'Name 3'
if Name == 'any name in the list':
print('Name is in the list')
How can I check if "Name 3" is in the list?
And also when the list looks like this:
list_1 = [
['Name 1'],
['Name 2'],
['Name 3']
]
Upvotes: 1
Views: 1227
Reputation: 12337
In both cases, use list comprehension
to flatten the list of lists in which you search, thus converting it into an ordinary list (in which you use in
to search for name
):
name = 'Name 3'
list_1 = [
['Name 1', 'Name 2', 'Name 3']
]
if name in [item for sublist in list_1 for item in sublist]:
print('Name is in the list')
list_1 = [
['Name 1'],
['Name 2'],
['Name 3']
]
if name in [item for sublist in list_1 for item in sublist]:
print('Name is in the list')
Note that as MisterMiyagi mentioned in the comment, you can also use set comprehension:
if name in {item for sublist in list_1 for item in sublist}:
print('Name is in the list')
Or you can use generator expression:
if name in (item for sublist in list_1 for item in sublist):
print('Name is in the list')
These are possibly faster and/or more memory-efficient than list comprehension under some circumstances, such as large lists, or lists with many duplicates.
SEE ALSO:
Generator expressions vs. list comprehensions
Upvotes: 2
Reputation:
Name = ''
Name_list = []
Name_list_v2 = []
if len(Name_list)==1:
Name_list_v2=Name_list[0]
elif len(Name_list)>1:
for names in Name_list:
Name_list_v2.append(names[0])
else:
print("Input formatted incorrectly")
for names in Name_list_v2:
if names == Name:
print("Name is in the list.")
else:
print("Name is not in the list")
Line by line description of what happens:
Name
variable[['Name 1', 'Name 2', 'Name 3']]
or [['Name 1'], ['Name 2'], ['Name 3']]
(you don't have to use three variables)Name_list_v2
, which will eventually be formatted as ['Name 1', 'Name 2', 'Name 3']
regardless of which way you chose to input it[['Name 1', Name 2', 'Name 3']]
, and if it is converts it into ['Name 1', 'Name 2', 'Name 3']
[['Name 1'], ['Name 2'], ['Name 3']]
, and if it is, change it to ['Name 1', 'Name 2', 'Name 3']
Names_list_v2
, and print a response.Upvotes: 0
Reputation: 10699
Use any
if any(Name in sublist for sublist in Name_list):
print('Name is in the list')
Upvotes: 1
Reputation: 360
Use
if Name in Name_list[0]:
print(Name)
The Name_list[0]
is because, you are creating a list inside a list. So, Name_list contains a list inside it. If you want to access the list inside Name_list, you will have to use the list index operator.
Upvotes: 1