Lists and Slicing in Python

Programming, for all ages and all languages.
Post Reply
mac
Member
Member
Posts: 144
Joined: Tue Sep 23, 2014 6:12 pm

Lists and Slicing in Python

Post by mac »

I need some beginner general programming help. I downloaded and was playing in the Python interpreter, reading the official Python tutorial docs. (V3.4)

I do get stumped when they start talking about manipulating strings and bring up subjects like slicing and indexing. I am already having issues processing the concepts.
Icee
Member
Member
Posts: 100
Joined: Wed Jan 08, 2014 8:41 am
Location: Moscow, Russia

Re: Lists and Slicing in Python

Post by Icee »

A string can be interpreted as a sequence of characters. Indexing is then accessing an individual character within a string. For instance, the string "hello" is a sequence of 5 characters, 'h', 'e', 'l', 'l', and 'o'. "hello"[0] refers to character at index 0, which is 'h' (indexing starts with 0 and counts up to string length - 1). Slicing is accessing a substring between two indexes. "hello"[0:2] refers to the substring starting at index 0 (inclusive) and ending before index 2 (i.e., exclusive). This substring is then "he". Given a string S of length N, S[0:N] is the whole string. When slicing, either of the two indexes can be omitted. Omitting the first index (as in "hello"[:3]) is the same as specifying it to be 0, i.e. the slice starts at the very start of the whole string. Omitting the second index (as in "hello"[3:]) starts the slice at given index and slices up to the end of the string (thus "hello"[3:] yields "lo").

You can think of indexing as of looking at a string written on paper through a small window that allows you to see only one character at a time. The window can be moved. Slicing can be visualized as a similar concept, but the window can also be resized.

Hope that helps.
mac
Member
Member
Posts: 144
Joined: Tue Sep 23, 2014 6:12 pm

Re: Lists and Slicing in Python

Post by mac »

But why isn't "Hello [0:2] seen as 'hel' instead of 'he' ?

Wait a minute, even though it counts from 0,they are sliced/indexed as if counting from 1 right?
alexfru
Member
Member
Posts: 1111
Joined: Tue Mar 04, 2014 5:27 am

Re: Lists and Slicing in Python

Post by alexfru »

Are you still evaluating multiple languages or are you trying to learn several at once? I'd advise against the latter.
User avatar
iansjack
Member
Member
Posts: 4685
Joined: Sat Mar 31, 2012 3:07 am
Location: Chichester, UK

Re: Lists and Slicing in Python

Post by iansjack »

It's just an arbitrary convention, the same as the fact that indexes start at 0 rather than 1 (although both conventions are chosen for good reasons). In a slice the first number is the first element of the slice, the second the first element beyond the slice.

It can also get a bit more complicated when you start considering negative indexes and assigning to slices. There's a discussion on Stack Exchange: http://stackoverflow.com/questions/5092 ... e-notation
User avatar
iansjack
Member
Member
Posts: 4685
Joined: Sat Mar 31, 2012 3:07 am
Location: Chichester, UK

Re: Lists and Slicing in Python

Post by iansjack »

alexfru wrote:Are you still evaluating multiple languages or are you trying to learn several at once? I'd advise against the latter.
That has its pros and cons. But Python is a better choice for a first language than C.
User avatar
Muazzam
Member
Member
Posts: 543
Joined: Mon Jun 16, 2014 5:59 am
Location: Shahpur, Layyah, Pakistan

Re: Lists and Slicing in Python

Post by Muazzam »

Try http://www.codecademy.com/ tutorials on Python and JavaScript (You might find JavaScript easy). These tutorials are interactive, hence good and have community support. Official guides are often not beginners-friendly.
Note: I am not advertising anything, I just find it helpful.
mac
Member
Member
Posts: 144
Joined: Tue Sep 23, 2014 6:12 pm

Re: Lists and Slicing in Python

Post by mac »

alexfru wrote:Are you still evaluating multiple languages or are you trying to learn several at once? I'd advise against the latter.
No, but I guess I need to "unlearn" everything else I read.
User avatar
Owen
Member
Member
Posts: 1700
Joined: Fri Jun 13, 2008 3:21 pm
Location: Cambridge, United Kingdom
Contact:

Re: Lists and Slicing in Python

Post by Owen »

SeanMc wrote:But why isn't "Hello [0:2] seen as 'hel' instead of 'he' ?

Wait a minute, even though it counts from 0,they are sliced/indexed as if counting from 1 right?
One needs to step back and consider the mathematical concept of intervals (or ranges).

Consider the interval with endpoints 0 and 10. Are the endpoints inside or outside the interval?
  • If the interval contains both endpoints, then it is considered to be closed. It's commonly notated as [0, 10]
  • If the interval excludes both endpoints, then it is considered to be open. It's commonly notated as (0, 10); though that's somewhat opaque, and I feel that the common alternate syntax ]0, 10[ is more clear.
  • If the interval contains some mix, then it's half-open/half-closed, e.g. [0, 10[ (Please ignore these closing brackets; they are because PHPbb is confused: ]])
When dealing with the infinite precision of abstract maths, the distinction is very important: There isn't a way to rewrite an open end as a closed end or vise-versa in the real numbers, for example. When dealing with finite precision numbers, as most of the time in programming, the choice is somewhat arbitrary and stylistic, however half open ranges of the form [0, 10[ are preferred because they have some advantages: (PHPbb is confused again: ]])
  • The starting end being closed just makes consistent sense. It would be weird if "hello"[0:2] returned "el", when hello[0] returns "h".
  • The finishing end being open makes many things easier. For example, a slice from x of length y becomes list[x:x+y]. If the choice of a closed finishing end had been made, this would have been list[x:x+y-1]. For the converse, the length of slice [x:y], the sum is merely y-x. A closed end would have made that y-x+1. Essentially, having the second end open makes common mathematical operations simpler
You'll find very similar decisions in most common programming languages.
User avatar
KemyLand
Member
Member
Posts: 213
Joined: Mon Jun 16, 2014 5:33 pm
Location: Costa Rica

Re: Lists and Slicing in Python

Post by KemyLand »

Summary:

In Python, the expression x[y:z] refers to a copy of the range of elements from y (inclusive) to z (exclusive) in the indexable object x.
Happy New Code!
Hello World in Brainfuck :D:

Code: Select all

++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.
[/size]
mac
Member
Member
Posts: 144
Joined: Tue Sep 23, 2014 6:12 pm

Re: Lists and Slicing in Python

Post by mac »

I'm beginning to find defining functions to be a very powerful feature and I've been messing around with it a few times.

Code: Select all

def print_greeting(s):
   print(s)
   print('your awesome')


print_greeting('welcome')

User avatar
KemyLand
Member
Member
Posts: 213
Joined: Mon Jun 16, 2014 5:33 pm
Location: Costa Rica

Re: Lists and Slicing in Python

Post by KemyLand »

SeanMc wrote:I'm beginning to find defining functions to be a very powerful feature and I've been messing around with it a few times.

Code: Select all

def print_greeting(s):
   print(s)
   print('your awesome')


print_greeting('welcome')

That's pretty good! Procedural programming (what you're doing with this) is the basis for C and thus eventually OSDev. Take in account that other programming paradigms can help you *a lot*, i.e: Object-Oriented Programming (this is like wine, it's good for you, as long as you don't abuse it!), Functional Programming (see Python's lambda expressions), and a long etc... Some languages (specially Python and C++, but most notabily Python) mix paradigms. That's a good model and has proved to be pretty self-sustainable. For example, you can have C-style functions in Python (not the parameters...), but if you need it, you can threat them as first-citizen objects (a property of Functional Programming) and use them as actual variables and arguments. You can also involve classes as deep as you want. Something that I like with Python, is that you can't abuse OOP, or you'll end up with un-maintainable code (i.e: def __init__(), with lots of self and references everywhere)!
Happy New Code!
Hello World in Brainfuck :D:

Code: Select all

++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.
[/size]
kzinti
Member
Member
Posts: 898
Joined: Mon Feb 02, 2015 7:11 pm

Re: Lists and Slicing in Python

Post by kzinti »

KemyLand wrote:Functional Programming (see Python's lambda expressions)
KemyLand wrote:you can threat them as first-citizen objects (a property of Functional Programming)
These things don't define functional programming. Just because you are using something called "lambda" in a given programming language doesn't make your program "functional". Nor is having functions as first-class objects make your language functional. The essence of functional programming is that you are dealing with immutable states. This can of course be accomplished in *any* language if you stay away from mutating anything. Of course, this isn't very efficient in Python where the philosophy is dramatically opposite: everything is mutable and can cause side-effects.

From http://en.wikipedia.org/wiki/Functional_programming:
In computer science, functional programming is a programming paradigm, a style of building the structure and elements of computer programs, that treats computation as the evaluation of mathematical functions and avoids changing-state and mutable data.
User avatar
KemyLand
Member
Member
Posts: 213
Joined: Mon Jun 16, 2014 5:33 pm
Location: Costa Rica

Re: Lists and Slicing in Python

Post by KemyLand »

Although you're right that Python isn't the "essence" of Functional Programming, I did just provided some examples of it in presented in the language. BTW, I've never liked the idea of "what Wikipedia says is the truth", neither that "because the majority says so, it's so" [-X . I don't like to relate Functional Programming with immutability. Although most functional-oriented programming languages do so, it limits your posibilities, as much as hard OOP does when lacking real procedures. Multi-paradigm languages are the future :wink: .
Happy New Code!
Hello World in Brainfuck :D:

Code: Select all

++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.
[/size]
kzinti
Member
Member
Posts: 898
Joined: Mon Feb 02, 2015 7:11 pm

Re: Lists and Slicing in Python

Post by kzinti »

KemyLand wrote: BTW, I've never liked the idea of "what Wikipedia says is the truth"
I understand the sentiment, but in this case I quoted Wikipedia because they happen to have a good and proper definition of functional programming.
KemyLand wrote:neither that "because the majority says so, it's so"
This isn't a popularity contest, "functional programming" has a specific meaning.
KemyLand wrote:I don't like to relate Functional Programming with immutability.
But that is precisely what functional programming is! The word "functional" in "functional programming" means that you program with functions (in the mathematical sense). A mathematical function has no state and returns a result (output) from it's arguments (input). There is no global state or variables anywhere in sight. You can't say you don't like it and redefine what "functional programming" means and expect people to agree.
KemyLand wrote:Although most functional-oriented programming languages do so,
Functional programming is a style of programming. The language can enfore it (i.e. Haskell) or not (i.e.: C, Python, ...)
Post Reply