I have a csv file and managed to get access to it and just get the 6th element of each row into a var (buys).
Now, I want to take these numbers in buys into a new list to take afterwards a random number of the list but I’m struggling creating a list. Can you help me please?
My code is now:
import csv import random data = open('data.csv') dataList = list(csv.reader(data, delimiter=',')) for item in dataList: buys = item buyslist = list(buys) randomNumber = random.choice(buyslist) print(buyslist)
and when I print buyslist I get each number into an element like 803 transfered into the list . But i need  :D.
It sounds like your goal is to select a random row and extract the value found at index
6 in that row. Right now, you’re trying to select a random digit from index
6 in every row.
What you want requires no explicit loop at all:
import csv import random with open('data.csv') as data: # Use with statement for deterministic cleanup dataList = list(csv.reader(data, delimiter=',')) randomNumber = random.choice(dataList) # Select random row, extract relevant column
If you need the whole
list of just that row, you can convert once up front, then perform the selection, replacing
randomNumber = random.choice(dataList) with:
buyslist = [item for item in dataList] # Simple listcomp to extract relevant column # from each row in new list # Optionally, convert to integer upfront with: buyslist = [int(item) for item in dataList] # listcomp to both extracts *and* parses randomNumber = random.choice(buyslist) # Select random value from extracted values