Jack Herer Jack Herer - 27 days ago 14
Python Question

Python 3 | Using Multiple if statements inside a for loop?

I have searched and found nothing that suits my needs.

I have three

for
loops that each has an
if
conditions inside it. Here is the code:

for friend in friends:
columns = friend.split("\n")
if len(columns) == 4:
c.execute("""INSERT INTO `fb_friends`(`name`, `no_of_mutual_friends`, `no_of_new_posts`, `already_friends`) VALUES (?, ?, ?, ?)""", (columns))

for friend in friends:
columns = friend.split("\n")
if len(columns) == 3:
c.execute("""INSERT INTO `fb_friends`(`name`, `no_of_mutual_friends`, `already_friends`) VALUES (?, ?, ?)""", (columns))

for friend in friends:
columns = friend.split("\n")
if len(columns) == 2:
c.execute("""INSERT INTO `fb_friends`(`name`, `no_of_mutual_friends`, `already_friends`) VALUES (?, ?, ?)""", (columns))


Is there a more efficient way of doing this? I was thinking of the
and
operator like so:

for friend in friends:
columns = friend.split("\n")
if len(columns) == 4:
c.execute("""INSERT INTO `fb_friends`(`name`, `no_of_mutual_friends`, `no_of_new_posts`, `already_friends`) VALUES (?, ?, ?, ?)""", (columns))
and
if len(columns) == 3:
c.execute("""INSERT INTO `fb_friends`(`name`, `no_of_mutual_friends`, `already_friends`) VALUES (?, ?, ?)""", (columns))
and
if len(columns) == 2:
c.execute("""INSERT INTO `fb_friends`(`name`, `already_friends`) VALUES (?, ?)""", (columns))


Can any one suggest the best or most efficient way of doing this as apposed to iterating three times over the same list?

Answer

Full code here:

for friend in friends:
    columns = friend.split("\n")
    if len(columns) == 4:
        c.execute("""INSERT INTO `fb_friends`(`name`, `no_of_mutual_friends`, `no_of_new_posts`, `already_friends`) VALUES (?, ?, ?, ?)""", (columns))
    elif len(columns) == 3:
        c.execute("""INSERT INTO `fb_friends`(`name`, `no_of_mutual_friends`, `already_friends`) VALUES (?, ?, ?)""", (columns))
    elif len(columns) == 2:
        c.execute("""INSERT INTO `fb_friends`(`name`, `already_friends`) VALUES (?, ?)""", (columns))