0

New to python and trying to figure out why the following 2 lists generate different output formats

n=5 mylist = "*" * n print(mylist) mylist = ["\*", "\*", "\*", "\*", "\*"] print(mylist) 

Output:

***** ['\*', '\*', '\*', '\*', '\*'] 
2
  • 1
    Just realized that mylist = "*" * n probably does not generate a list Commented Jun 4, 2017 at 1:51
  • No it does not. It creates a string object made by concatenating ' *' + ' *' +.. n times. It's still a string object though. Commented Jun 4, 2017 at 1:54

4 Answers 4

2

"*" * 5 gives you a string of length 5.

["*"] * 5 gives you a list of five strings of length 1.

In both of these cases, the result has the same type as the "input," just five times longer.

Sign up to request clarification or add additional context in comments.

Comments

0

Your first variable is a string and the second is a list.

When you do "*" and multiply it by n you multiply that character n times and it returns a string.

The second one you declared as a list and is thus, printed as a list.

Comments

0

In Python when using a multiplication operator (*) with a string this string is repeated according to the number, for example

str = "-" * 6 # output : ------

NOTE : This operation returns a string and not a list

The second output is simply a list with elements and its output is as expected

I hope I have helped

Comments

0

My output is

***** ['\\*', '\\*', '\\*', '\\*', '\\*'] 

Obviously,"*" * n is a string,["\*", "\*", "\*", "\*", "\*"] is a list. If you want to create a list, please set a list first.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.