-1

How to create a list of string using range() built-in function in python?

range(1,7) produces a range object equivilant to [1,2,3,4,5,6]

Desired list: ['1','2','3','4','5','6']

5
  • 5
    range(7) does not output [1,2,3,4,5,6]. Commented Jul 27, 2018 at 4:34
  • It doesn't even output a list ;) Commented Jul 27, 2018 at 4:42
  • If you mark it as duplicate you should link to a duplicate Commented Jul 27, 2018 at 4:48
  • 1
    The link is above the question Commented Jul 27, 2018 at 5:27
  • @ᴡʜᴀᴄᴋᴀᴍᴀᴅᴏᴏᴅʟᴇ3000, it does in python 2 Commented Jul 27, 2018 at 5:34

4 Answers 4

5

Use a cast to str() & list comprehension as per the following:

string_list = [str(x) for x in range(1, 7)]
Sign up to request clarification or add additional context in comments.

1 Comment

you want range(1, 7) since OP wants the list to start at '1'.
4

With the map function:

list(map(str,range(7)))

1 Comment

Or [*map(str,range(7))]. But your solution is much more readable.
2

Or the new f-strings:

>>> [f'{i}' for i in range(7)]
['0', '1', '2', '3', '4', '5', '6']

1 Comment

Note this is python 3.6+
1

Use string formatting & list comprehension as per the following

string_list = ["{}".format(x) for x in range(1,7)]

3 Comments

You don't need the full functionality of str.format here - str(x) would have worked just as well as "{}".format(x). Also, if you wanted to start from 1, your range call is wrong.
Even if you need a format spec (which you don't, since you aren't using one), you still wouldn't want to use str.format here; just call format(x, "03") instead of "{:03}".format(x). You only need str.format to put multiple things together. And even then, f-strings are usually better: f"{x:03}".
@user2357112, I have fixed the range call. and you are right about the use of str(x) it is also a solution

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.