user4409008
user4409008

Reputation:

Adding object to a list with a for loop?

I've done my research on stack overflow and could not find an answer that works out for me even though similar questions have been posted in the past. My issue is that I want to add string values that I am getting from a for loop that goes through a list and matches to a regular expression. I want to add them to a combined list of values, I am using a clean function that works on the submission of a form but when the data prints into my terminal it comes out like this:

   ['#example']
   ['#test']

when I want those values to print like this:

   ['#example', '#test',]

Here's my code in my views.py

      def clean(self):
        data = self.cleaned_data
        regex = re.compile("\B#\w\w+")
        tweeters = data['tweets']
        split_tweets = tweeters.split()
        for x in split_tweets:
           if re.search(regex, x):
            master_list = [x]
            print master_list

Upvotes: 0

Views: 49

Answers (3)

John La Rooy
John La Rooy

Reputation: 304185

You need to append to a list, otherwise you are just throwing away all the previous values

  def clean(self):
      data = self.cleaned_data
      regex = re.compile("\B#\w\w+")
      tweeters = data['tweets']
      split_tweets = tweeters.split()
      master_list = []
      for x in split_tweets:
          if re.search(regex, x):
              master_list.append(x)
      print master_list

You can also use a list comprehension here instead

  def clean(self):
      data = self.cleaned_data
      regex = re.compile("\B#\w\w+")
      tweeters = data['tweets']
      split_tweets = tweeters.split()
      master_list = [x for x in split_tweets if re.search(regex, x)]
      print master_list

Upvotes: 2

TigerhawkT3
TigerhawkT3

Reputation: 49318

You're doing some strange things with that assignment. Why do you keep reassigning a list? Initialize the list before the loop, append() to it inside the loop, and print the whole thing after the loop.

master_list = []
for x in split_tweets:
   if re.search(regex, x):
    master_list.append(x)
print master_list

Upvotes: 1

YOBA
YOBA

Reputation: 2807

Do this instead:

  def clean(self):
    data = self.cleaned_data
    regex = re.compile("\B#\w\w+")
    tweeters = data['tweets']
    split_tweets = tweeters.split()
    master_list = []
    for x in split_tweets:
       if re.search(regex, x):
        master_list.append(x)
    print master_list

You need to append elements to the list instead of affecting a new "one element list" [x] to master_list, it get overridden by the next value

Upvotes: 1

Related Questions