-4

I tried using all the methods suggested by others but its not working. methods like str.split(), lst = list("abcd") but its throwing error saying [TypeError: 'list' object is not callable]

I want to convert string to list for each character in the word input str= "abc" should give list = ['a','b','c']

I want to get the characters of the str in form of list output - ['a','b','c','d','e','f'] but its giving ['abcdef']

str = "abcdef"
l = str.split()
print l
  • @MYGz :TypeError: 'list' object is not callable – Abhishek Priyankar Jan 16 '17 at 06:58
  • @AbhishekPriyankar Rule1: Don't keep variable names equal to Python keywords. `s1 = "abcdef"; l1=list(s1); print l1` – Mohammad Yusuf Jan 16 '17 at 08:40
  • Thanks Got it. :) – Abhishek Priyankar Jan 16 '17 at 09:29
  • 1
    @MYGz Technically, `list` isn't a keyword, it's just the name of a built-in type. If you try to assign to a keyword eg, `class`, `for`, `in`, `with`, etc you'll get a syntax error. This question is a great example of why it's a Bad Idea to use built-in type names as variable names. It _can_ work, but when it doesn't work the error message can be bewildering, especially to newbies who aren't fully conversant with what Python's error messages mean, and only newbies are likely to use built-in type names as variable names. – PM 2Ring Jan 16 '17 at 10:11
  • @PM2Ring Thanks for dispelling the fallacy my statement was spreading :D – Mohammad Yusuf Jan 16 '17 at 10:14

4 Answers4

2

First, don't use list as a variable name. It will prevent you from doing what you want, because it will shadow the list class name.

You can do this by simply constructing a list from the string:

l = list('abcedf')

sets l to the list ['a', 'b', 'c', 'e', 'd', 'f']

cco
  • 5,873
  • 1
  • 16
  • 21
0

First of all, don't use list as name of the variable in your program. It is a defined keyword in python and it is not a good practice.

If you had,

str = 'a b c d e f g'

then,

list = str.split()
print list
>>>['a', 'b', 'c', 'd', 'e', 'f', 'g']

Since split by default will work on spaces, it Will give what you need.

In your case, you can just use,

print list(s)
>>>['a', 'b', 'c', 'd', 'e', 'f', 'g']
Harish Talanki
  • 866
  • 13
  • 27
0

Q. "I want to convert string to list for each character in the word"

A. You can use a simple list comprehension.

Input:

new_str = "abcdef"

[character for character in new_str]

Output:

['a', 'b', 'c', 'd', 'e', 'f']
nipy
  • 5,138
  • 5
  • 31
  • 72
0

Just use a for loop.

input:::

str="abc"
li=[]
for i in str:
    li.append(i)
print(li)
#use list function instead of for loop    
print(list(str))

output:::

["a","b","c"]
["a","b","c"]