2

I was debugging some python code and as any begginer, I'm using print statements. I narrowed down the problem to:

paths = ("../somepath") #is this not how you declare an array/list?
for path in paths:
    print path

I was expecting the whole string to be printed out, but only . is. Since I planned on expanding it anyway to cover more paths, it appears that

paths = ("../somepath", "../someotherpath")

fixes the problem and correctly prints out both strings.

I'm assuming the initial version treats the string as an array of characters (or maybe that's just the C++ in me talking) and just prints out characters.?...??

I'd still like to know why this happens.

9
  • () is used for tuples, list is [] Commented Dec 11, 2014 at 10:10
  • a list would be ["../somepath"] Commented Dec 11, 2014 at 10:10
  • Do any other languages declare single element arrays/tuples with brackets like that and also handle the use of brackets for their many other purposes? Commented Dec 11, 2014 at 10:17
  • @jamylak C++ and C use {}. I'm new to dynamic typing. Commented Dec 11, 2014 at 10:46
  • @jamylak: Note that sometimes you don't even need the parentheses to make a tuple, eg a=3,4,5. Commented Dec 11, 2014 at 10:50

3 Answers 3

5
("../somepath")

is nothing but a string covered in parenthesis. So, it is the same as "../somepath". Since Python's for loop can iterate through any iterable and a string happens to be an iterable, it prints one character at a time.

To create a tuple with one element, use comma at the end

("../somepath",)

If you want to create a list, you need to use square brackets, like this

["../somepath"]
Sign up to request clarification or add additional context in comments.

1 Comment

the OP wants to create an array/list
0
paths = ["../somepath","abc"]

This way you can create list.Now your code will work .

paths = ("../somepath", "../someotherpath") this worked as it formed a tuple.Which again is a type of non mutable list.

Comments

0

Tested it and the output is one character per line

So all is printed one character per character

To get what you want you need

# your code goes here
paths = ['../somepath'] #is this not how you declare an array/list?
for path in paths:
    print path

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.