Home > Mobile >  behaviour difference between list() function and [] in a conditional, the former behaves like string
behaviour difference between list() function and [] in a conditional, the former behaves like string

Time:01-06

Why does list(str) behaves as string here when [str] doesn't?

Is there a difference between these methods

enter image description here

Before someone marks this as a duplicate do link the answer because I've spent a fair bit of time scrawling through stackoverflow!

code

x = 'ar'
'a' in list(x)
#True
'a' in [x]
#False
l = list(x)
'a' in l
#True
type(list(x))
#list
type([x])
#list

CodePudding user response:

This is because list() converts the string to a list where each letter is one element. But [] creates a list where the things inside are the elements. List() is converting the string to a list whereas [] is just putting the string in a list.

CodePudding user response:

Because you are asking if the element 'a' is in the list. Which it is not, your only element is 'ar'. If you print([x]) the result should be ['ar']

CodePudding user response:

[x] creates a single-element list, where the element is x. So if x = 'ar', then the resulting list is ['ar'].

list(x) casts the variable x into a list. This can work on any iterable object, and strings are iterable. The resulting list is ['a', 'r'].

The element 'a' is in the second list but not the first.

CodePudding user response:

You can use debug output for clarifying such things. Like this:

x = 'ar'
print(list(x))
print([x])

Prints this:

['a', 'r']
['ar']

Then let's think logically. list(x) is a constructor of a list from the string, it creates a list of all characters of a given string. And [x] just creates a list with one item: x.

  •  Tags:  
  • Related