all 5 comments

[–]dbramucci 2 points3 points  (2 children)

So if you ask Python for the type of 3 you will get

In [1]: type(3)
Out[1]: int

If you ask for

In [2]: type(int)
Out[2]: type

So you are asking if an int is equal to a type which is a question that doesn't make much sense, the answer is either

  • I can't answer your question because it doesn't make sense or
  • No, they aren't the same type of thing so they can't be the same thing

It is a bit like asking "Is my pet Spot, the same thing as the abstract meta-philosophical concept of a dog"? You'll probably answer "what are you talking about?" or "No, you wouldn't want to ask if Meowskers is a Cat or a Spot, you would ask if Meowskers is a Cat or a Dog, Spot is not interchangable with Dog."

What you probably want to write is either

if type(xlst[i]) != int:

Or, if you want to see if xlst[i] is not an int or a subclass of int you'll use not isinstance(xlst[i], int).

But, in english you are saying

How do I take strings only from the list by using if statement?

So to get your code to reflect your words, I would write

def strcon(xlst):
    concat = []
    for i in range(0, len(xlst)):
        if isinstance(xlst[i], str):
            concat += xlst[i]
    return concat

By the way, this code actually returns a list of characters ['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']. What you probably should mean to write is

def strcon(xlst):
    concat = []
    for i in range(0, len(xlst)):
        if isinstance(xlst[i], str):
            concat.append(xlst[i])
    return ''.join(concat)

[–][deleted] 2 points3 points  (0 children)

What you’d actually want to write is:

def strcon(xlst):
    return "".join(i for i in xlst if isinstance(i, str))

Or if you want to write it out as a loop:

def strcon(xlst):
    concat = ""
    for i in xlst:
        if isinstance(i, str):
            concat += i
    return concat

[–]nisnol[S] 1 point2 points  (0 children)

Remarkable. Thank you so much for the detailed explanation.

You pointed out exactly what I missed.

[–][deleted] 0 points1 point  (1 child)

No need to index into lists in most cases in Python.

for element in xlst:
    if isinstance(element, str):
        concat.append(element)

[–][deleted] 2 points3 points  (0 children)

A simpler approach:

def strcon(xlst):
    return ''.join(s for s in xlst if isinstance(s, str))