Laire
Laire

Reputation: 35

Check if a list is the exactly the same as the tuple

I was trying to make a program that if the user entered the exactly same data with the given tuple, it will print ('available'), else, if not, it will append the new data. But my program doesn't print 'available' even though I entered the exactly same data too.

data = ['Karma', 19, 'e', 'Kunugigaoka JH']
user = [input('name:'), int(input('age: ')), input('section: '), input('school: ')]
if user in data: 
    print('still available')
else: 
    data = data.append(user), print(data, 'your new data is now added')

What's the wrong code there? Was it the 'in' in the if statement, and how to fix it? Thank you

Upvotes: 2

Views: 75

Answers (3)

Ubdus Samad
Ubdus Samad

Reputation: 1215

This answer is completly based on the title of this question:

Let's say you have:

>>>a = [1,2,3] #REMEMBER for this method to work the list and tuple should be in exact oder
>>>b = (1,2,3)

>>>all( [i==j for i,j in zip(a,b)] )
True
>>>b = (3,2,1) #Here though a and b have the same elements but not the same order
>>>all( [i==j for i,j in zip(a,b)] )
Flase

Upvotes: 0

jpp
jpp

Reputation: 164673

Below is a functioning version of your code.

data = [['Karma', 19, 'e', 'Kunugigaoka JH']]
user = [input('name:'), int(input('age: ')), input('section: '), input('school: ')]

if user in data:
    print('still available')
else:
    data.append(user)
    print(user, 'your new data is now added')

Explanation

  • Your data format needs to be a list of lists in order for your program to work as anticipated.
  • list.append does not return anything, so do not assign to a variable.

Upvotes: 3

Stephen Rauch
Stephen Rauch

Reputation: 49794

in will check each element of your data. So in the case of:

data = ['Karma', 19, 'e', 'Kunugigaoka JH']

it will check 'Karma', then 19, then...

Instead you should try:

data = [['Karma', 19, 'e', 'Kunugigaoka JH']]

This is a list, in a list. Now the first thing in will check will be:

['Karma', 19, 'e', 'Kunugigaoka JH']

Upvotes: 1

Related Questions