1

Whats the difference between creating a list through a method like

x= list('')

and this

x = ['']

Here is the code if I use list [] to make a list it will think every letter is wrong but if I use list() it works perfectly fine

    mainword = input("Enter your word").lower()
    builtword = ''
    number = list(mainword)
   
    correctLetters = list(number)
    buildword2 = ['']

    userGuess = input("Guess letter").lower()
    print(userGuess)

    while builtword != mainword:
    if userGuess in correctLetters:

    print('That was correct')
    x = number.find(userGuess)
    print(x)

    builtword = builtword+userGuess.lower()
    print(builtword)
    if builtword != mainword:
        userGuess = input("Guess letter").lower()

else:
    print('sorry that\'s wrong try again')
    userGuess = input("Guess letter").lower()

print("Congratulations you finished the word was "+mainword.capitalize())'''
  • `[]` is faster and more idiomatic. Bytecode is different. Only use `list()` for conversions. Difference can be seen by `dis`: `dis.dis('[]')` and `dis.dis('list()')`. – ggorlen Feb 11 '21 at 22:54
  • 1
    This is similar to [Python basics why set() works but {} fails?](https://stackoverflow.com/q/65836354/674039) – wim Feb 11 '21 at 23:08

1 Answers1

2

The two expressions are not equivalent.

list('') iterates over each character of the string, turning an empty string into an empty list:

>>> list('')
[]

[''] creates a list containing a single, empty string.

>>> ['']
['']

If the string is not empty, it's a bit easier to see the effect:

>>> list('123')
['1', '2', '3']
>>> ['123']
['123']
Fred Larson
  • 60,987
  • 18
  • 112
  • 174
  • How would I find a specific thing in the first example, like for example I wanted to find which space 2 was in since .find() does not work. –  Feb 11 '21 at 23:15
  • You could try the [`index` method](https://docs.python.org/3/tutorial/datastructures.html) of `list`. – Fred Larson Feb 11 '21 at 23:23