Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #63109

Re: Strange behaviour with a for loop.

References <4DC5A4FC-CCAF-446B-B41C-23E52C2389B6@icloud.com>
Date 2014-01-04 16:18 +1100
Subject Re: Strange behaviour with a for loop.
From Chris Angelico <rosuav@gmail.com>
Newsgroups comp.lang.python
Message-ID <mailman.4889.1388812744.18130.python-list@python.org> (permalink)

Show all headers | View raw


On Sat, Jan 4, 2014 at 3:03 PM, Sean Murphy <mhysnq1964@icloud.com> wrote:
>   filenames = sys.argv[1:]
>
> for filename in filenames:
>   print ("filename is: %s\n" %filename)

versus

>   filenames = sys.argv[1]
>
> for filename in filenames:
>   print ("filename is:  %s\n" % filename)

The first one is slicing sys.argv, so it returns another list. For
instance, sys.argv might be:

['foo.py', 'test', 'zxcv']

in which case sys.argv[1:] would be:

['test', 'zxcv']

which is still a list. But sys.argv[1] is a single string:

'test'

Now, when you use that in a for loop, you iterate over it. Iterating
over a list yields its items, as you'd expect. Iterating over a string
yields its characters. That's why you see it spelled out. Instead of
iterating over a list of file names, you're iterating over a single
file name, which isn't (in this case) all that useful.

Does that explain what you're seeing?

ChrisA

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

Re: Strange behaviour with a for loop. Chris Angelico <rosuav@gmail.com> - 2014-01-04 16:18 +1100

csiph-web