JustBenji
JustBenji

Reputation: 73

List - Index Out Of Range

I'm trying to get familiar with python, I've been converting some C# code over into python and I've ran into an error i can't figure out, i'm getting a "Index Out Of Range" error, this is my python code:

import random

myString = raw_input("Input: ")

words = myString.split(" ")
wordList = list()

for word in words:
    wordList.append(word) 

wordChoice = 0;
myStringRandomized = "";

while len(wordList) != 0:
    wordChoice = random.randint(0, len(wordList))
    myStringRandomized += wordList[wordChoice] + " "
    del wordList[wordChoice]

print("Characters: " + str(len(myString)))
print("Words: " + str(len(myString.split(" "))))
print("Uppercase: " + myString.upper())
print("Lowercase: " + myString.lower())
print("Randomized: " + myStringRandomized)

And the working equivalent in C#:

static void Main(string[] args)
{
    Console.Write("Input: ");
    string myString = Console.ReadLine();

    string[] words = myString.Split(' ');
    List<string> wordList = new List<string>();

    foreach (string word in words)
        wordList.Add(word);

    Random random = new Random();

    int wordChoice = 0;
    string myStringRandomized = "";

    while (wordList.Count != 0)
    {
        wordChoice = random.Next(0, wordList.Count);
        myStringRandomized += wordList[wordChoice] + " ";
        wordList.Remove(wordList[wordChoice]);
    }

    Console.WriteLine("Characters: " + myString.Length);
    Console.WriteLine("Words: " + myString.Split(' ').Length);
    Console.WriteLine("Uppercase: " + myString.ToUpper());
    Console.WriteLine("Lowercase: " + myString.ToLower());
    Console.WriteLine("Randomized: " + myStringRandomized);
    Console.ReadKey();
}

It would be great if someone could point out where I've gone wrong, thank you very much!

Upvotes: 0

Views: 87

Answers (1)

jonrsharpe
jonrsharpe

Reputation: 121966

Per the documentation, random.randint can include the value of b (in this case, len(wordList)). Instead, you should use random.randrange, which is half-open (like range) and won't include the stop value (and, as 0 is the default start, you can leave it out).

Upvotes: 4

Related Questions