Use a dictionary for a variable number of variables

The Pythonic solution is to use collections.defaultdict:

from collections import defaultdict

d = defaultdict(list)

for item in original_list:
    d[item['amenity']].append(item)

print(d['Pool'])

[{'amenity': 'Pool', 'amount': 300, 'id': 5, 'percentage': 10, 'version': 2},
 {'amenity': 'Pool', 'amount': 200, 'id': 2, 'percentage': 10, 'version': 1}]

print(d['Parking'])

[{'amenity': 'Parking', 'amount': 120, 'version': 1, 'percentage': 4, 'id': 1}]

My intention is that when I order them in that way I can get the object with the greatest version per list using a lambda equation.

You can use a dictionary comprehension with max for this task:

res = {k: max(v, key=lambda x: x['version']) for k, v in d.items()}

{'Parking': {'amenity': 'Parking',
  'amount': 120,
  'id': 1,
  'percentage': 4,
  'version': 1},
 'Pool': {'amenity': 'Pool',
  'amount': 300,
  'id': 5,
  'percentage': 10,
  'version': 2}}
Answer from jpp on Stack Overflow
🌐
PyTutorial
pytutorial.com › split-list-of-objects-by-attribute-in-python
PyTutorial | Split List of Objects by Attribute in Python
November 26, 2024 - # Split using list comprehension ... to filter(), while achieving the same result. The groupby() function from itertools is useful for grouping objects by an attribute....
Discussions

python - Split list into sub-lists based on attribute value - Stack Overflow
I have an array of objects that have a suit attribute, and I want to split into sub arrays based on which suit the object has. I currently am using this: for c in cards: if c.suit.val... More on stackoverflow.com
🌐 stackoverflow.com
qgis - I am looking for a Python method to Split the list of attributes in a layer - Geographic Information Systems Stack Exchange
I have a list of attributes in QGIS: [137.0, u'0101S', u'MUNICIPIO', u'28004', 19849.4753178, 22000935.5836, u'\Alamo, El'] And I am trying to obtain each element in the list, using pyqgis. I can... More on gis.stackexchange.com
🌐 gis.stackexchange.com
April 14, 2016
python - Splitting a list of objects into n lists while keeping all attributes - Stack Overflow
I'm trying to code a class method that takes every nth item and puts into a separate list. Then puts each of those lists into a separate object, all with the same attributes as the original object ... More on stackoverflow.com
🌐 stackoverflow.com
python - How to slice a list of objects in association of the object attributes - Stack Overflow
I have a list of fixtures.Each fixture has a home club and a away club attribute.I want to slice the list in association of its home club and away club.The sliced list should be of homeclub items and More on stackoverflow.com
🌐 stackoverflow.com
People also ask

How do I fix 'NoneType object has no attribute'?
The variable you're accessing is None, but you expected an object. Trace back to where it was assigned: a function returning None instead of an object (forgot to return), a database query returning no rows (Model.objects.first() returns None when empty), or an API call that failed silently. Safe pattern: if obj is not None: obj.method() OR use the walrus operator: if (obj := get_obj()): obj.method().
🌐
itsourcecode.com
itsourcecode.com › home › attributeerror: ‘list’ object has no attribute ‘split’ [solved]
Fix List() Object has no Attribute Split (2026 Python)
What is Python AttributeError and what causes it?
AttributeError is raised when you access an attribute or method that doesn't exist on the object. Most common cause: calling a method on None (NoneType has no attribute X). Other causes: typo in method name, wrong object type (str when you expected list), or using a feature removed in a newer library version. The error names exactly which type and which missing attribute.
🌐
itsourcecode.com
itsourcecode.com › home › attributeerror: ‘list’ object has no attribute ‘split’ [solved]
Fix List() Object has no Attribute Split (2026 Python)
How do I prevent AttributeError from None values?
Three patterns: (1) Always validate function returns (if result is None: raise). (2) Use type hints with Optional[X] to make None-ability explicit. (3) Use the walrus operator + early return: if (val := get_val()) is None: return default; use val. Defensive coding around None-able returns prevents 90% of AttributeError in production.
🌐
itsourcecode.com
itsourcecode.com › home › attributeerror: ‘list’ object has no attribute ‘split’ [solved]
Fix List() Object has no Attribute Split (2026 Python)
🌐
Stack Overflow
stackoverflow.com › questions › 61292745 › split-list-of-objects-by-object-attribute
python 3.x - Split list of objects by object attribute - Stack Overflow
from collections import groupby grouped_car_list= groupby(car_list, key = lambda car : car.type) for type , cars in grouped_car_list: print(type) print("=============================") for car in cars: car.show() ... Find the answer to your ...
Top answer
1 of 3
9

Although it is not a one-liner, by using a list, we make it more elegant:

spades, diamonds, clubs, hearts = collcard = [[] for _ in range(4)]

for c in cards:
    collcard[c.suit.value].append(c)

Here we thus initialize a list with four empty sublists, then we append the card c to the list with index c.suit.value.

We use iterable unpacking to assign the first element to spades, the second to diamonds, etc.

The advantage is that we avoid sorting (which works in O(n log n)). So this algorithm has time complexity O(n) (given the amortized cost of list appending is O(1)).

Although oneliners are usually elegant, one should not put to much effort in writing these, since oneliners can be harder to understand, or have significant impact with respect to performance.

2 of 3
9

When iterated upon, itertools.groupby yields tuple objects: the key, and an iterable of the grouped values (allowing lazy evaluation of the data).

You just converted the tuple to a list, which isn't very useful.

Instead, you need to drop the key (for instance by unpacking it to _, pythonic way of telling that you're not using it) and force iteration on the values:

[list(g) for _,g in itertools.groupby(cards, lambda x: x.suit.value)]

now if you want to group and sort, it's not very efficient to pass sorted(cards) to groupby just for the pleasure to create a one-liner (one-liners are nice, but I prefer fast programs). Your approach works, or you can also use collections.defaultdict, and even name the dict with the proper color using an indirection, for instance like this:

import collections

cards = collections.defaultdict(list)
colors = ["spades","diamonds","clubs","hearts"]

for c in cards:
    cards[colors[c.suit.value]].append(c)
🌐
Easy Tweaks
easytweaks.com › fix-attributeerror-list-has-no-attribute-split
'list' object has no attribute 'split' in Python
April 2, 2022 - Master meetings, chats, channels and online collaboration · Go beyond the basics in Word, Excel, PowerPoint and Outlook
🌐
Itsourcecode
itsourcecode.com › home › attributeerror: ‘list’ object has no attribute ‘split’ [solved]
Fix List() Object has no Attribute Split (2026 Python)
July 12, 2026 - Defensive coding around None-able returns prevents 90% of AttributeError in production. ... Browse the AttributeError reference hub for 170+ specific fixes (NoneType, pandas, NumPy, sklearn, Selenium). For related errors see TypeError. For Python debugging fundamentals see Python Tutorial hub. ... attributeerror: 'list' object has no attribute 'split' can be easily solved by making sure you’re not using the split() method on list objects or non-string objects.
Find elsewhere
🌐
Career Karma
careerkarma.com › blog › python › python attributeerror: ‘list’ object has no attribute ‘split’ solution
Python attributeerror: ‘list’ object has no attribute ‘split’ Solution
December 1, 2023 - You solve this error by ensuring you only use split() on a string. If you read a file into a program, make sure you use split() on each individual line in the file, rather than a list of all the lines.
🌐
Reddit
reddit.com › r/learnpython › 'list' object has no attribute 'split'
r/learnpython on Reddit: 'list' object has no attribute 'split'
July 17, 2020 -

ive researched and found no help for this exact attribute error, error is on line 'songs = song.split()'

any help would be greatly appreciated

score = 0

read = open("songs.txt", "r")

song = read.readlines()

songs = []

for i in range(len(songs)):

songs.append(song[i].strip('\n'))

lives = 3

while lives <=3:

for i in range(len(songs)):

songs.append(song[i].strip('\n'))

artists = song[0]

songsies = song[1]

letters = [word[0] for word in songs]

print(artists , ''.join(letters))

choice = random.choice(song)

artists ,songies = choice.split(' - ')

songs = song.split()

for i in range(len(songs)):

songs.append(song[i].strip('\n'))

print(artists, ''.join(letters))

guess = str(input('Guess the song'))

🌐
Reddit
reddit.com › r/learnpython › "attributeerror: 'list' object has no attribute 'split'"
r/learnpython on Reddit: "AttributeError: 'list' object has no attribute 'split'"
April 22, 2021 -

I get this error while running my code

def use(filename,option="r"):
  with open(filename, option) as file:
  print(file.readlines().split("\n"))

my file for this example is a markdown file

The .md file is filled with random bs

# HEADER ONE

HEADER TWO

HEADER THREE

HEADER FOUR

HEADER FIVE

HEADER SIX

Some codeExamples see below:

function small(a,target){
  let isValid = null;
  if(a<=target>){
    isValid = true;
  }
  else{
    isValid = false;
  }
  console.log(`Is valid: ${isValid}`)
  return a <= target
}

But when I run it, I get

Traceback (most recent call last):

File "main.py", line 6, in <module>

use("a.md")

File "main.py", line 3, in use

print(file.readlines().split("\n"))

AttributeError: 'list' object has no attribute 'split'

🌐
TechGeekBuzz
techgeekbuzz.com › home › blog › programming language › python attributeerror: 'list' object has no attribute 'split' solution
Python AttributeError: 'list' object has no attribute 'split' Solution
The list does not support the split method. It is a string method that converts a string value into a list by separating the string based on the separator passed in the split() method.
🌐
sebhastian
sebhastian.com › attributeerror-list-object-has-no-attribute-split
Fix Python AttributeError: 'list' object has no attribute 'split' | sebhastian
January 3, 2023 - When you need to split elements inside a list, you can use the for loop to iterate over the list and call the split() method on the string values inside it. I'm sending out an occasional email with the latest tutorials on programming, web ...
🌐
GeeksforGeeks
geeksforgeeks.org › python-split-list-into-lists-by-particular-value
Split list into lists by value - Python - GeeksforGeeks
April 28, 2025 - Explanation: lambda x: x == b creates groups of True (when equal to b) or False (when not equal). It then checks for False groups and appends them to the result list, effectively splitting the list at occurrences of b and keeping only the segments ...
🌐
YouTube
youtube.com › watch
AttributeError list object has no attribute split in Python - YouTube
Download this code from https://codegive.com Title: Understanding and Resolving AttributeError: 'list' object has no attribute 'split' in PythonIntroduction:...
Published: November 15, 2023
🌐
Researchdatapod
researchdatapod.com › home › python attributeerror: ‘list’ object has no attribute ‘split’
Python AttributeError: ‘list’ object has no attribute ‘split’ - The Research Scientist Pod
June 10, 2022 - If you want to use split(), ensure that you iterate over the items in the list of strings rather than using split on the entire list. If you are reading a file into a program, use split() on each line in the file by defining a for loop over the lines in the file. To learn more about getting substrings from strings, go to the article titled “How to Get a Substring From a String in Python“. For further reading on AttributeErrors, go to the articles: How to Solve Python AttributeError: ‘int’ object has no attribute ‘split’
🌐
W3Schools
w3schools.com › python › ref_string_split.asp
Python String split() Method
The split() method splits a string into a list. You can specify the separator, default separator is any whitespace. Note: When maxsplit is specified, the list will contain the specified number of elements plus one.
🌐
Bobby Hadz
bobbyhadz.com › blog › python-attributeerror-list-object-has-no-attribute-split
AttributeError: 'list' object has no attribute 'split' | bobbyhadz
April 8, 2024 - To solve the error, you either ... sure to call split() on a string, or call split() on an element in the list that is of type string. You can either access the list at a specific index, e.g. my_list[0] or use a for loop to iterate over the list if you have to call split() on each element. You can view all the attributes an object has by using the dir() function...