Removing square brackets and parenthesis from numbers inside a list in Python

I want to remove all quotation marks and square brackets from this list so I get only integers I can work with.

original =  ['1', '2', [3], '3', 4, '5', 6]

My attempt:

integers = list(map(int, original.split(',')))
print(integers)

What I expected to happen:

new_lst = [ 1 , 2 , 3, 3 ,4 , 5 ,6]

What actually happened:
I am stucked!

AttributeError: 'list' object has no attribute 'split'

Do you understand why you got that error?

Is it only strings and lists that can be elements of original? Will each of these elements have a length of 1?

My understanding is that I have different types of data inside the list. I have strings . Ex: ‘1’ ; I have integers. Ex: 4 ; and I have a number 3 inside square brackets. Is this read as a list? Anyway, I have tried lots of thing and nothing works. How would you approach this problem? I need a list of just integers, as my next step is to make a dictionary separating odds from evens in their own lists.
Much appreciated!

Yeah, that’s a list.

Concerning what you shared above, it’s failing because you’re using str.split on a list with original.split(','), that doesn’t work.

I understand your goal, but I don’t understand where you’re coming from. This helps in providing an adequate answer. I can give you something that works, but you may not understand, or I can give you something that works and you can understand. For the latter, I need more context.

Is this a task you have at work? Self-learning? Does it come from a course? What have you covered until now?

Hi @alejandra.orcutt and welcome to the community!

Although I’m sure @Bruno probably has a much more elegant solution, the way I solved this problem was to create a for loop where I tested if each element was a list and if it was, used list.pop() to remove the elements and added them to the final desired list. If the element was not a list (tested using isinstance(element, list)) then simply appended the element to the final list after casting said element to an integer.

As I said, not the most clever solution but it does work and can be tweaked to handle situations where nested lists have more than one element.

Hi Bruno, it is an assignment. I have been coding for two weeks. Pretty new to this. I was given the following lists:

lst1 = ['1', '2', [3]]

lst2 = [('3'), (4), '5', 6]

INSTRUCTION: Join lst1 and lst2 so only unique string or integer values remain in a new list, lst3.(i.e., [‘1’, ‘2’, 3, ‘3’, 4, 5, 6])

  1. MY FIRST STEP

lst3 = lst1 + lst2 # I made a single list by concatenating
print(lst3) # output, [‘1’, ‘2’, [3], ‘3’, 4, ‘5’, 6]

  1. MY SECOND STEP : I believe I have to convert all to integers, so I did a bunch of FOR LOOPs. See below:
for p in lst3:
    lst3_last = int(lst3.pop())
    print('last digit', lst3_last)  # 6 5 4 3

for n in lst3[3:6]:
    lst3_end = int(n)
    print(lst3_end)  # 6 5 4 3 vertically
    print("list end ", type(lst3_end))  # <class 'int'> this printed 4 times

for f in lst3[2]:
    lst3_middle = int(f)
    print('list middle', lst3_middle)  # 3
    print(type(lst3_middle))  # <class 'int'>

for x in lst3[0:2]:
    lst3_first = int(x)
    print('list first', lst3_first)  # 1 2
    print(type(lst3_first))  # <class 'int'>
  1. MY THIRD STEP : I am trying to join the pieces to ving it back into a list. By the way, the extend() is greying out, so I am a bit confused.
lst3_first.extend(lst3_middle)  # the extend() function is greying out. 
lst3_first. extend(lst3_end)
lst3_first. extend(lst3_last)

Thanks Bruno, there has to be a more efficient way !

I worked with your idea, but I didn’t quite understand the process. I uploaded the entire thing in my reply to @bruno . Thank you :slight_smile:

This is very interesting because what you’re trying to do doesn’t match these instructions. Also, there appears to be an inconsistency within the example in the instructions. Or maybe it’s a typo. Let’s look at it together.

From the above instructions, it appears that our final list can be made up of unique integers or string values. This is important because until now, part of our strategy involved casting all elements as integers in our final list. It seems we don’t need this step.

However, the “i.e., [‘1’, ‘2’, 3, ‘3’, 4, 5, 6]” part of the instructions concerns me a little because it looks like the only difference between this output and the output from print(lst3) are two elements: the third element ([3]) and the second to last element ('5').

['1', '2',  3 , '3', 4,  5 , 6] # desired output
['1', '2', [3], '3', 4, '5', 6] # output from lst3

Can you double check the instructions to make sure they are correct? Is it possible that the solution to this entire problem is simply: lst3 = lst1 + lst2? I ask this because lst3 seems very close to the “desired output” at this point.

That said, if the instructions are correct and we need to create a new list ['1', '2', 3 , '3', 4, 5 , 6] from the existing lists lst1 = ['1', '2', [3]] and lst2 = [('3'), (4), '5', 6] it seems odd that we need to convert the list [3] to the integer 3 and to convert the string '5' to the integer 5 but not convert any of the other elements of lst3.

1 Like

FYI - I’m not sure what software you’re using to write your code but I’m guessing it is greying out extend() because that is a method used on lists and you’re trying to use it on integers.

I should also point out that this strategy is a bit dangerous because lst3.pop() will modify the lst3 list in place and so with each iteration of the loop, lst3 is being changed. Also, because lst3 is getting shorter with each iteration, you only get a total of 4 iterations because for p in lst3 “works from front to back” whereas lst3.pop() “works from back to front.” If you want to use lst3.pop() on the entire list, it’s better to use for p in range(len(lst3)). And lastly, any time you store a value in a variable within a for loop, be aware that the variable will be overwritten on each iteration of the loop. For example, lst3_last, lst3_end, and lst3_first have all had their values overwritten at least once but lst3_middle is being assigned a value inside a loop that only executes once since lst3[2] is just one element (i.e. 3)

It looks like your strategy in MY SECOND STEP above is to store individual elements and then rebuild the list using individual values. If you’d like to continue with that strategy after fixing the problems I just mentioned above, you can rebuild the list using individual elements like this:

final_list = [lst3_first, lst3_second, lst3_third, lst3_fourth, lst3_fifth, lst3_sixth]
1 Like

I did try the normal concatenation at first lst3 = lst1 + lst2 , but what I am supposed to do with the list is what got me confused. I am copy-pasting the instructions.

  • Create an empty dictionary called odds_evens. Next, iterate through lst3. If a number (regardless of datatype) is even, add the value to a list that will be stored as a value for the key even in the dictionary, odds_evens. Do the same for the odds numbers. When you print the odds_evens dictionary the output
    should look like this: {‘evens’: [‘2’, 4, 6], ‘odds’: [‘1’, ‘3’, 3, ‘5’]}

Am I getting closer?

lst1 = ['1', '2', [3]]
lst2 = [('3', 4), '5', 6]

lst3 = lst1 + lst2  
['1', '2', [3], '3', 4, '5', 6]

odds_evens ={}

  evens =[ ]
  odds = [ ]
for even in lst3:
    number = float(lst3) # TypeError: float() argument must be a string or a real number, not 'list'
    if number % 2 ==0:
        evens. append(number)

    if number % 2 != 0:
        odds.append(number)

    if odds == number:
        print(odds_evens.append(number))

@alejandra.orcutt Just a couple questions to make sure we’re on the same page…

  1. Did your teacher provide instructions for the first half of the problem describing the concatenation process?
  2. Are you familiar with list comprehensions?
  3. Have you used the isinstance() function before?
  4. Have you done a similar problem working with lists in your course?

I finally figured it out.

lst3 = lst1 +lst2  # I made a single list by concatenating
print(lst3)  # output, ['1', '2', [3], '3', 4, '5', 6]

print(type(lst3))
lst3.remove([3])  
print(lst3)
odds = [ ]
evens = [ ]

for number in lst3:
    number = int(number)
    if number % 2 == 0:
        evens. append(number)
    else:
        odds.append(number)

odds_evens = {"evens": evens, "odds": odds}

print(odds_evens)  #  {'evens': [2, 4, 6], 'odds': [1, 3, 5]}

Try this solutions.

original = [‘1’, ‘2’, [3], ‘3’, 4, ‘5’, 6]

Solution: 1

new_lst = list()

for num in original:

if isinstance(num, list):

    for x in num:

        new_lst.append(x)

elif isinstance(num, str):

    new_lst.append(int(num))

else:

    new_lst.append(num)

print(new_lst)

Solution: 2

new_list = [int(x) for x in str(original) if str.isdigit(x)]

print(new_list)

1 Like

while working with displaying the contents of list, the square brackets, both opening and closing are undesired. For this when we need to print whole list without accessing the elements for loops, we require a method to perform this. Let’s discuss a shorthand by which this task can be performed.

Method : Using str() + list slicing
The shorthand that can be applied, without having need to access each element of list is to convert the entire list to string and then strip the initial and last character of list using list slicing. This won’t work if list contains a string. In that case, each element can be joined using join()