-2

I have a list looks like below

 list_val = ['1','2','3','4']

I want to remove the square bracket and single quotes from the list. I like to get the output as like below

list_new = 1,2,3,4

Is it possible? Looking forward for quick help. Thanks in advance.

  • possible duplicate of (or very similar to) [Need to join the elements of a list but keep the '' around element after joining](http://stackoverflow.com/questions/23458448/need-to-join-the-elements-of-a-list-but-keep-the-around-element-after-joining) – vaultah Jan 03 '15 at 13:50
  • 1
    Your question doesn't make sense. The square brackets and commas are the syntax for list literals, the quotes are the syntax for string literals. You can get `[1, 2, 3, 4]` by making the list elements integers. Without square brackets, it's a tuple, not a list. What exactly are you trying to achieve? – jonrsharpe Jan 03 '15 at 14:07
  • @jonrsharpe I thought the expected result was a new list having integer value of list_val but expected answer was to just print string format `list_new = 1,2,3,4` which makes no sense. Thanks – Tanveer Alam Jan 03 '15 at 14:11

3 Answers3

3

For output, don't use the Python repr-esentation. Here, use join:

list_val = ['1','2','3','4']
print 'list_new = %s' % ','.join(list_val)
martineau
  • 119,623
  • 25
  • 170
  • 301
Daniel
  • 42,087
  • 4
  • 55
  • 81
0

Simple

list_new = [int(x) for x in list_val]
user590028
  • 11,364
  • 3
  • 40
  • 57
  • @@user590028: I tried list_new = [int(x) for x in list_val] but I got this error ValueError: invalid literal for int() with base 10: 'halloo' – questions post Jan 03 '15 at 13:58
  • 2
    @questionspost that looks nothing like the example in your question - you might want to update it to be more representative of real data – Jon Clements Jan 03 '15 at 13:59
0
list_new = 1,2,3,4

This expression is equivalent to tuple assignment.

>>> list_val = ['1','2','3','4']
>>> list_new = tuple(map(lambda x:int(x), list_val))
>>> list_new
(1, 2, 3, 4)

Is equivalent to :

>>> list_new = 1, 2, 3, 4
>>> list_new
(1, 2, 3, 4)
Tanveer Alam
  • 5,185
  • 4
  • 22
  • 43