:: operation in [1::2]

This is the place for queries that don't fit in any of the other categories.

:: operation in [1::2]

Postby pygene » Fri Mar 15, 2013 4:10 pm

Guys,
I'm a python newbie, and I'm wondering if someone could explain what the operation :: in [1::2] is called and what it does? I understand this is operation on list and what the code does is it prints out the even number lines.

Thanks.
Code: Select all
with open('file.txt','r') as f:
...   print ''.join(f.readlines()[1::2])
pygene
 
Posts: 4
Joined: Fri Mar 15, 2013 2:51 pm

Re: :: operation in [1::2]

Postby Yoriz » Fri Mar 15, 2013 4:52 pm

That means [start:stop:step] if you leave any empty, start defaults to the first item, stop defaults to the end and step defaults to 1
[1::2] is return the items from index 1 to the last item with a step of 2
New Users, Read This
Join the #python-forum IRC channel on irc.freenode.net!
Spam topic disapproval technician
Windows7, Python 2.7.4., WxPython 2.9.5.0., some Python 3.3
User avatar
Yoriz
 
Posts: 565
Joined: Fri Feb 08, 2013 1:35 am
Location: UK

Re: :: operation in [1::2]

Postby pygene » Fri Mar 15, 2013 4:55 pm

Thanks for the quick reply and explanation, got it!
pygene
 
Posts: 4
Joined: Fri Mar 15, 2013 2:51 pm

Re: :: operation in [1::2]

Postby setrofim » Fri Mar 15, 2013 4:55 pm

To illustrate:
Code: Select all
>>> my_list = [1,2,3,4,5,6,7,8]
>>> my_list[1::2]
[2, 4, 6, 8]
setrofim
 
Posts: 285
Joined: Mon Mar 04, 2013 7:52 pm


Return to General Coding Help

Who is online

Users browsing this forum: No registered users and 1 guest