Why does python show a typeError in [ ] and not in ( )?

Question: I know that ( ) is used as a tuple (variable containing multiple values) & [
] is for a list in python. My question is in the following scenario when I used a tuple the code worked but when I used a list it showed a typeError. Why? Plus, Why do we use string formatting anyway? What is actually string formatting and what does it do? If it is string formatting then why is there a %d that formats integers?

The First attempt with tuple:

data = ("John", "Doe", 53.44)
format_string = "Hello %s %s. Your current balance is $%s."

print(format_string % data)

The Output:

    Hello John Doe. Your current balance is $53.44.

The second attempt with list:

data = ["John", "Doe", 53.44]
format_string = "Hello %s %s. Your current balance is $%s."

print(format_string % data)

The output:

TypeError: not enough arguments for format string

My question is we can use lists in string formatting then why doesn’t it work here?

Thank You

When using % to format string and there’s more than one value required, then the values have to be in tuple.
I don’t know if there’s any specific reasoning for that. Only thing that comes to mind is that tuples are immutable. See more about it: Built-in Types — Python 3.11.3 documentation

Keep in mind formatting with % is an old way to format strings in python. Currently there’s newer ways to do that - .format method and the f-strings.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.