steff
steff

Reputation: 906

Python looping when there is only one item in the list

Hello i need to loop over a few accounts but sometimes there is only one account. What is the best way to do that please?

Here is what i tried but this fails when there is only one account in the list.

accounts = ('X123456','Y325252')
for account in accounts:
    do stuff

Sorry about the beginners question.

Upvotes: 3

Views: 10124

Answers (3)

AreToo
AreToo

Reputation: 1335

A Python for loop will iterate over each item in a tuple or each character in a string. A string in parentheses is just a string. Python doesn't realize it's a tuple unless there is a comma within the parentheses.

Example:

In : tuple1 = ('this', 'that') 
In : tuple2 = ('this')
In : tuple3 = ('this',)

In : tuple1[0]
Out: 'this'

In : tuple2[0]
Out: 't'

In : tuple3[0]
Out: 'this'


In : for item in tuple2:
...:     print(item)
...: 
t
h
i
s

In : for item in tuple3:
...:     print(item)
...: 
this

Upvotes: 1

Treyten Carey
Treyten Carey

Reputation: 661

If you really want to use parenthesis to initialize a tuple, add a comma in there like so: a = ("bc",).

If there is only one item without a comma, Python returns only the single item, and then the for-loop iterates through each character. I.E a = ("b", "c") returns ('b','c') and a = ("bc") returns bc.

a = ("b", "c");
print(a);     # ('b', 'c')
a = ("bc");
print(a);     # bc

Instead, you could use either braces or brackets, or add a comma as shown above. These are always treated as a tuple (or list).

accounts = ['X123456','Y325252']
for account in accounts:
    do stuff

Upvotes: 3

Mark Tolonen
Mark Tolonen

Reputation: 177735

You have to provide a one-element list or tuple. Any of the following will work:

accounts = 'X123456', # one-element tuple 
accounts = ('X123456',) # also tuple
accounts = ['X123456'] # list

Note the comma makes the tuple, not the parentheses, which is why you can leave them out.

Upvotes: 2

Related Questions